Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataBinding with an conditional expression

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.

like image 269
Manvinder Avatar asked Dec 15 '22 06:12

Manvinder


1 Answers

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

like image 143
Pavel Voronin Avatar answered Jan 11 '23 18:01

Pavel Voronin