我有一个组合框,我希望在未选中复选框时启用它。我怎么写呢?我试过跟随,但似乎WPF无法识别这种语法:
<ComboBox IsEnabled={Binding Path=!CheckBoxIsChecked, Mode=OneWay}/>
<CheckBox IsChecked={Binding Path=CheckBoxIsChecked}/>
答案 0 :(得分:1)
您必须编写转换器,即实现IValueConverter接口的类。然后将转换器分配给绑定的Converter属性:
<ComboBox IsEnabled="{Binding Path=CheckBoxIsChecked, Mode=OneWay, Converter={StaticResource MyConverter}}"/>
答案 1 :(得分:1)
你应该使用所谓的转换器来做这些事情。
{Binding ElementName=CheckBox, Path=IsChecked, Converter=BoolToVisibilityConverter}
BoolToVisibilityConverter是一个标准的WPF转换器。您也可以轻松编写OppositeBoolToVisibilityConverter。网上有很多例子。
答案 2 :(得分:1)
您必须使用转换才能实现此目的。
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>
答案 3 :(得分:-1)
触发器应该也能正常工作:
<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>