带条件表达式的 WPF 数据绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18542120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:32:43  来源:igfitidea点击:

WPF DataBinding with an conditional expression

wpfdata-bindingmvvm

提问by MegaMind

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.

我正在使用 MVVM 模式,我的视图的数据上下文有一个属性 Customer。现在我想根据 Customer.CustomerID 属性的值绑定我的文本框的 IsEnabled 属性。如果它大于 0,则应启用否则禁用。

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.

我知道我可以轻松地在视图模型中添加一个 bool 属性并将其绑定到我的文本框的 IsEnabled 属性,但这似乎有点矫枉过正。

回答by Pavel Voronin

There are several options.

有几种选择。

First, you can use DataTrigger

首先,您可以使用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 的 setter 中的值只能覆盖样式 setter 中设置的值。如果您直接设置该值,则触发器将不起作用。
原因是Dependency Property Value Precedence

DataTriggerworks only with equality condition, so if you need to check against the negative numbers aswell, then use second option - Value Converter

DataTrigger仅适用于相等条件,因此如果您还需要检查负数,请使用第二个选项 -值转换器