wpf - 将可见性绑定(bind)到 Text.Length

标签 wpf xaml

我实现了一个小的视觉指示器(只是一个带边框的文本 block ),如果此时没有要显示的文本,它应该被隐藏。文本绑定(bind)到 Indicator 属性,数据上下文似乎设置正确。

到目前为止我得到的是这个(出现指示文本,隐藏/显示不起作用):

<Border>
    <Border.Style>
        <Style TargetType="{x:Type Border}">
            <Setter Property="Visibility" Value="Visible"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Indicator.Length}" Value="0">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <TextBlock Text="{Binding Indicator}" />
</Border>

我的问题是,如果文本长度为零,则元素不会被隐藏。

你发现我的错误了吗?

指示器是相应 View 模型的一部分:

public string Indicator
{ get; set;}

更新

如果我将上面的属性更改为:

public const string IndicatorPropertyName = "Indicator";
private string _indicator = "";
public string Indicator
{
    get
    { return _indicator;}

    set
    {
        if (_indicator == value) { return;}

        RaisePropertyChanged(IndicatorPropertyName);
    }
}

为什么只有在我引发 PropertyChanged 事件时它才有效?

最佳答案

我认为顾名思义,触发器仅在事件发生时执行或检查其状态。 在 DataTrigger 的情况下,它是接口(interface) INotifyPropertyChangedPropertyChanged 事件。

如果不引发事件,DataTrigger 不知道他必须检查绑定(bind)以及值是否满足触发条件。

关于wpf - 将可见性绑定(bind)到 Text.Length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13680951/

相关文章:

c# - 尝试使用 EventAggregator 时 Caliburn.Micro 的 DisplayRootViewFor 方法中的 NullReferenceException

c# - Objective-C <-> 单桥

c# - WPF跨线程消息框不阻塞主线程输入

wpf - 路径数据属性的M,L,XAML是什么

c# - WPF:ListView 中列表属性的总和

.net - SQL Azure 分页优化

c# - 2 个 XAML 使用相同的 ViewModel 类,但有 2 个单独的实例

c# - 将鼠标悬停在控件上时显示标签中的文本而不使用事件

c# - 如何在 WPF MVVM 中将 View 的变量绑定(bind)到 ViewModel?

c# - 将函数绑定(bind)到 xaml 中的 MouseDown 事件?