I would like to bind the IsEnabled property of a ComboBox to the IsChecked property of a checkbox, while I want the ComboBox to be ENABLED only when the checkbox value is FALSE.
IsEnabled="{Binding ElementName=RegexCbx, Path=IsChecked}"
What's the simplest way for doing that?
Use style trigger:
<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>
A class derived from IValueConverter should do the trick:
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
}
Preferably in a Resource Dictionary, create an instance of the converter:
<converters:BoolToOppositeBoolConverter x:Key="oppositeBoolConverter" />
Then in your view, do something like this where the bool value for IsChecked gets converted to the opposite value. Don't forget to include the resource dictionary as a resource for the view.
<TextBox IsEnabled="{Binding IsChecked, Converter={StaticResource oppositeBoolConverter}" />
Another way to do that, is to use Blend 's 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.