I am using MVVM pattern and my datacontext of my view is having a property Customer. Now I want to bind IsEnabled property of my textbox based on the value of Customer.CustomerID property. If it is greater than 0 then it should be enable else disable.
I understand I could easily add a bool property in the view model and bind it to the IsEnabled property of my textbox but that seems to be an overkill.
There are several options.
First, you can use DataTrigger
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Customer.CustomerID}" Value="0" >
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
<TextBox>
Be aware, please, that value from DataTrigger's setter can override only the value set in style setter. If you set the value directly then trigger won't work.
The reason is Dependency Property Value Precedence.
DataTrigger
works only with equality condition, so if you need to check against the negative numbers aswell, then use second option - Value Converter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With