我有一個組合框,並且我希望在複選框未選中時啓用它。我如何編寫它?我試過以下,但似乎WPF不承認這句法:WPF綁定中的公式
<ComboBox IsEnabled={Binding Path=!CheckBoxIsChecked, Mode=OneWay}/>
<CheckBox IsChecked={Binding Path=CheckBoxIsChecked}/>
我有一個組合框,並且我希望在複選框未選中時啓用它。我如何編寫它?我試過以下,但似乎WPF不承認這句法:WPF綁定中的公式
<ComboBox IsEnabled={Binding Path=!CheckBoxIsChecked, Mode=OneWay}/>
<CheckBox IsChecked={Binding Path=CheckBoxIsChecked}/>
觸發應該工作一樣好這個:
<CheckBox IsChecked="{Binding Path=CheckBoxIsChecked}" />
<ComboBox Grid.Row="1" ItemsSource="{Binding Path=ComboItems}" SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}">
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=CheckBoxIsChecked}" Value="False" >
<Setter Property="IsEnabled" Value="True"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=CheckBoxIsChecked}" Value="True" >
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
不會喜歡這個解決方案,因爲已經提到過。與應用程序中多個位置的多個編輯器相比,這是更多的代碼和更少的可維護性。 – 2012-01-27 18:25:58
你必須寫一個轉換器,即一類,它實現了IValueConverter接口。轉換器將被分配到您的綁定的轉換器屬性:
<ComboBox IsEnabled="{Binding Path=CheckBoxIsChecked, Mode=OneWay, Converter={StaticResource MyConverter}}"/>
編寫一個屬性比較容易CheckBoxIsNotChecked {get {return!CheckBoxIsChecked; }} – 2012-01-27 13:23:54
是的,但是如果綁定到一個你自己不寫的對象,也就是說你無法控制這組屬性? – Clemens 2012-01-27 13:25:20
這是一個好點 – 2012-01-27 13:27:08
您應該使用所謂的轉換器來做這些事情。
BoolToVisibilityConverter是一個標準的WPF轉換器。您也可以輕鬆編寫一個OppositeBoolToVisibilityConverter。網上有很多例子。
你將不得不使用轉換器來實現這一點。
public class BooleanNegationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ConvertValue(value);
}
private bool ConvertValue(object value)
{
bool boolValue;
if(!Boolean.TryParse(value.ToString(), out boolValue))
{
throw new ArgumentException("Value that was being converted was not a Boolean", "value");
}
return !boolValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ConvertValue(value);
}
}
然後使用它是這樣的:
<ComboBox IsEnabled="{Binding Path=CheckBoxIsChecked,
Mode=OneWay,
Converter={StaticResource BooleanNegationConverterKey}}"/>
記住,你必須聲明在XAML資源這個靜態資源。就像這樣:
<UserControl.Resources>
<ResourceDictionary>
<BooleanNegationConverter x:Key="BooleanNegationConverterKey" />
</ResourceDictionary>
</UserControl.Resources>
我相信更通用的方法將被引入InverseBooleanConverter([見這裏](http://stackoverflow.com/a/1039681/485076))並在需要的地方使用它,而不是在多個視圖中複製粘貼觸發器 – sll 2012-01-27 13:53:01
[如何在WPF中綁定反布爾屬性?](http://stackoverflow.com/questions/1039636/how -to-bind-inverse-boolean-properties-in-wpf) – sll 2012-01-27 13:53:53