WPF数据绑定:基于var的内容启用/禁用控件?

问题描述:

我的表单上有一个按钮,只有在树状视图(或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 属性的按钮到成员的内容var?也就是说,如果成员var不为空,则启用该按钮。

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.

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

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.