我想将ComboBox的IsEnabled属性绑定到复选框的IsChecked属性,而我希望仅当复选框值为FALSE时才能使用ComboBox。
IsEnabled="{Binding ElementName=RegexCbx, Path=IsChecked}"
这样做最简单的方法是什么?
答案 0 :(得分:3)
使用样式触发器:
<StackPanel>
<CheckBox x:Name="Foo" Content="Click me"/>
<ComboBox>
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=Foo}" Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
</StackPanel>
答案 1 :(得分:1)
从IValueConverter派生的类应该可以解决这个问题:
public class BoolToOppositeBoolConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
最好在资源字典中,创建转换器的实例:
<converters:BoolToOppositeBoolConverter x:Key="oppositeBoolConverter" />
然后在您的视图中,执行类似这样的操作,其中IsChecked的bool值将转换为相反的值。不要忘记将资源字典包含为视图的资源。
<TextBox IsEnabled="{Binding IsChecked, Converter={StaticResource oppositeBoolConverter}" />
答案 2 :(得分:0)
另一种方法是使用 Blend 的DataTrigger
:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ie="http://schemas.microsoft.com/expression/2010/interactions"
<ComboBox>
<i:Interaction.Triggers>
<ie:DataTrigger Binding="{Binding IsChecked, ElementName=RegexCbx}"
Value="False">
<ie:ChangePropertyAction PropertyName="IsEnabled"
TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBox}}"
Value="True"/>
</ie:DataTrigger>
<ie:DataTrigger Binding="{Binding IsChecked, ElementName=RegexCbx}"
Value="True">
<ie:ChangePropertyAction PropertyName="IsEnabled"
TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBox}}"
Value="False"/>
</ie:DataTrigger>
</i:Interaction.Triggers>
</ComboBox>