如何在Visibility属性上执行简单的XAML(WPF)条件绑定 [英] How to do a simple XAML (WPF) conditional binding on the Visibility property

查看:104
本文介绍了如何在Visibility属性上执行简单的XAML(WPF)条件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有属性的视图模型:

I have got a view model with a property:

public class MyModel
{
    public bool IsEnabled {get;set;}
}

我想使用此属性来切换按钮状态.如果布尔值为true,我想隐藏该按钮,否则将其显示.

I want to use this property to toggle a button state. If the boolean is true I want to hide the button, and otherwise show it.

我尝试过类似的事情:

<Button Visibility= "{Binding IsEnabled ? Hidden : Visible  }">Enable</Button>

但这不合适.

我尝试了一些更复杂的解决方案,但我的猜测是,我缺少一些琐碎的东西.

I tried some more complex solution but my guess is, I am missing something trivial.

有什么建议吗?

推荐答案

由于要在 Hidden Visible 之间切换,并且true处于隐藏状态,因此您可以编写自定义 IValueConverter 或使用简单的 Style.Trigger

Since you want to toggle between Hidden and Visible and true is hidden you can either write custom IValueConverter or use simple Style.Trigger

<Button Content="Enable">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Visibility" Value="Visible"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsEnabled}" Value="True">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>                    
        </Style>
    </Button.Style>
</Button>

这全部是假设相应地设置了 DataContext 并且 MyModel.IsEnabled 每次更改都会引发 INotifyPropertyChanged.PropertyChanged 事件

This is all assuming the DataContext is set accordingly and MyModel.IsEnabled raises INotifyPropertyChanged.PropertyChanged event whenever changed

public class MyModel : INotifyPropertyChanged
{
    private bool _isEnabled;

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            _isEnabled = value;
            OnPropertyChanged("IsEnabled");
        }
    }

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

这篇关于如何在Visibility属性上执行简单的XAML(WPF)条件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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