WPF DataBinding与条件表达式 [英] WPF DataBinding with an conditional expression

查看:280
本文介绍了WPF DataBinding与条件表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVVM模式,我的视图的datacontext拥有一个属性Customer。现在我想根据Customer.CustomerID属性的值绑定我的文本框的IsEnabled属性。如果它大于0,那么应该启用其他禁用。



我明白我可以轻松地在视图模型中添加一个bool属性,并将其绑定到IsEnabled属性

解决方案

有几个选项。



首先,您可以使用 DataTrigger

 < TextBox> 
< TextBox.Style>
< Style TargetType =TextBox>
< Setter Property =IsEnabledValue =True/>
< Style.Triggers>
< DataTrigger Binding ={Binding Customer.CustomerID}Value =0>
< Setter Property =IsEnabledValue =False/>
< / DataTrigger>
< /Style.Triggers>
< / Style>
< /TextBox.Style>
< TextBox>请注意,DataTrigger设置器中的值可以只覆盖样式设置器中设置的值。

如果直接设置值,则触发器将无法正常工作。
原因是依赖属性值优先权



DataTrigger 仅在相等条件下工作,因此如果您需要检查反对负数,然后再使用第二个选项 - 价值转换器


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

这篇关于WPF DataBinding与条件表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆