由于您可能希望基于字符串绑定按钮的 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, Type targetType, object parameter, 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。