WPF数据绑定:启用/禁用基于VAR的内容的控制权? [英] WPF Data Binding : enable/disable a control based on content of var?

查看:163
本文介绍了WPF数据绑定:启用/禁用基于VAR的内容的控制权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的窗体上的按钮时,在一个TreeView(或在TabItem的列表视图)选中一个项目只应启用。当选择了一个项目,它的值存储在一个字符串成员变量。

I have a button on my form that should only be enabled when an item is selected in a treeview (or the listview in a tabitem). When an item is selected, it's value is stored in a string member variable.

我可以绑定 IsEnabled 属性的按钮部件变种的内容?也就是说,如果该成员变种是不空的,启用按钮。

Can I bind the IsEnabled property of the button to the content of the member var? That is, if the member var is not empty, enable the button.

同样,当成员VAR的内容更改(设置或清除),按钮的状态会改变。

Similarly, when the content of the member var changes (set or cleared), the button's state should change.

推荐答案

既然你可能希望基于字符串按钮的IsEnabled属性绑定,尝试制作一个转换器吧。

Since you're probably looking to bind the IsEnabled property of the button based on a string, try making a converter for it.

IE浏览器...


<StackPanel>
<StackPanel.Resources>
<local:SomeStringConverter mystringtoboolconverter />
</StackPanel.Resources>
<Button IsEnabled="{Binding ElementName=mytree, Path=SelectedItem.Header, Converter={StaticResource mystringtoboolconverter}}" />
<StackPanel>

和转换器:



[ValueConversion(typeof(string), typeof(bool))]
    class SomeStringConverter : IValueConverter {
    	public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
    		string myheader = (string)value;
    		if(myhead == "something"){
    			return true;
    		} else {
    			return false;
    		}
    	}

    	public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
    		return null;
    	}
    }



编辑:
自在OP想绑定到一个变量,需要像这样做:

Since the OP wanted to bind to a variable, something like this needs to be done:



public class SomeClass : INotifyPropertyChanged {
  private string _somestring;

  public string SomeString{
    get{return _somestring;}
    set{ _somestring = value; OnPropertyChanged("SomeString");}
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

}

然后,改变上述绑定表达式为:

Then, change the above binding expression to:


{Binding Path=SomeString, Converter={StaticResource mystringtoboolconverter}}

请注意,你必须实现INotifyPropertyChanged为你的UI进行更新。

Note, you MUST implement INotifyPropertyChanged for your UI to be updated.

这篇关于WPF数据绑定:启用/禁用基于VAR的内容的控制权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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