I would like to bind a ComboBox with a CheckBox so that the ComboBox is enabled when the CheckBox is not checked . Can I do that directly in the xaml file, without adding any additional variable in the code?
In the code below, myComboBox is enabled when myCheckBox is ckecked .
<ComboBox Name="myComboBox" SelectedIndex="0"
IsEnabled="{Binding ElementName=myCheckBox, Path=IsChecked}">
You need a converter to convert the Boolean values to it's inverted value. In order to do that first create a class the inherits from IValueConverter like this:
public sealed class InvertedBooleanConverter : IValueConverter
{
public Object Convert( Object value, Type targetType, Object parameter, CultureInfo culture )
{
if ( value is Boolean )
{
return (Boolean)value ? false : true;
}
return null;
}
public Object ConvertBack( Object value, Type targetType, Object parameter, CultureInfo culture )
{
throw new NotImplementedException();
}
}
Then you need to add the converter in the resources like this:
<Window.Resources>
<local:InvertedBooleanConverter x:Key="InvertedBooleanConverter" />
</Window.Resources>
And lastly just add the converter to the binding like this:
<ComboBox Name="myComboBox"
SelectedIndex="0"
IsEnabled="{Binding ElementName=myCheckBox, Path=IsChecked, Converter={StaticResource InvertedBooleanConverter}}">
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.