我的表单上有一个按钮,只有在树状视图(或tabitem中的列表视图)中选择项目时才应启用.当选择项目时,它的值存储在字符串成员变量中.
可以将按钮的IsEnabled属性绑定到成员var的内容吗?也就是说,如果成员var不为空,则启用该按钮.
类似地,当成员的内容变化(设置或清除)时,按钮的状态应该改变.
解决方法
由于您可能希望基于字符串绑定按钮的IsEnabled属性,请尝试为其创建转换器.
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,CultureInfo culture ) {
return null;
}
}
编辑:
由于OP想要绑定到变量,所以需要这样做:
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));
}
}
}
然后,将上述绑定表达式更改为:
{Binding Path=SomeString,Converter={StaticResource mystringtoboolconverter}}
注意,你必须实现INotifyPropertyChanged为你的UI更新.