c# - 如何根据条件将 VIew 模型的属性绑定(bind)到 DataTrigger Setter?

标签 c# wpf data-binding setter datatrigger

我有一个 TextBox,如果 TextBox 有 Text.Length >0 那么我必须更改 HasChar 属性 True 否则 False。在这里我无法在 Setter 中绑定(bind)属性。

XAML 源代码:

<TextBox Text="WPF">
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Value="0"
                    Binding="{Binding Text.Length, RelativeSource={RelativeSource Self}}">
                    <Setter Property="{Binding HasChar}" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

View 模型 C# 源代码:

private bool _hasChar= true;
public bool HasChar
{
    get { return _hasChar; }
    set
    {
        _hasChar= value;
        OnPropertyChanged();
    }
}

最佳答案

你在滥用触发器。
正确的做法:

1) XAML:

<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>

2) 查看模型。您不需要将 setter 添加到 HasChar。如果此属性绑定(bind)到 View 中的某些内容,只需引发适当的 PropertyChanged:

public class ViewModel : INotifyPropertyChanged
{
    // INPC implementation is omitted

    public string Text
    {
        get { return text; }
        set
        {
            if (text != value)
            {
                text = value;
                OnPropertyChanged();                    
                OnPropertyChanged("HasChar");
            }
        }
    }
    private string text;

    public bool HasChar
    {
        get { return !string.IsNullOrEmpty(Text); }
    }
}

关于c# - 如何根据条件将 VIew 模型的属性绑定(bind)到 DataTrigger Setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34390477/

相关文章:

c# - if 语句有 2 个条件

c# - 旋转形状以跟随 wpf 中的光标

c# - 使用类型填充组合框

java - XMLMapper.ReadValue 返回具有有效 xml 和空值的 NPE

c# - 重新连接后继续 FTP 下载

c# - 试图在c#中获取链表的特定节点的地址

wpf - StackPanel : why do auto and * behave strangely? 内的网格

c# - 以编程方式使用具有指定位置和大小的 Windows 资源管理器打开文件夹 [C#]

WPF 绑定(bind) IsSelected 到 ViewModel 不会设置列表中未显示的项目

c# - SortDescription 和自动排序顺序刷新