WPF DataBinding with an conditional expression

后端 未结 1 447
盖世英雄少女心
盖世英雄少女心 2021-01-14 15:01

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.Custo

相关标签:
1条回答
  • 2021-01-14 15:21

    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

    0 讨论(0)
提交回复
热议问题