Reputation: 26952
I have a combobox, and I want it to be enabled when checkbox is not checked. How do I write it? I tried following, but it seems that WPF doesn't recognise this syntax:
<ComboBox IsEnabled={Binding Path=!CheckBoxIsChecked, Mode=OneWay}/>
<CheckBox IsChecked={Binding Path=CheckBoxIsChecked}/>
Upvotes: 2
Views: 759
Reputation: 5655
You should use so-called converters to do these kind of things.
{Binding ElementName=CheckBox, Path=IsChecked, Converter=BoolToVisibilityConverter}
BoolToVisibilityConverter is a standard WPF converter. You can also easily write a OppositeBoolToVisibilityConverter. Many examples around on the net.
Upvotes: 1
Reputation: 1333
A trigger should work just as well for this:
<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>
Upvotes: -1
Reputation: 5605
You will have to use convertor to achieve this.
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);
}
}
Then use it like this:
<ComboBox IsEnabled="{Binding Path=CheckBoxIsChecked,
Mode=OneWay,
Converter={StaticResource BooleanNegationConverterKey}}"/>
Remember you have to declare this static resource in xaml resources. Like this:
<UserControl.Resources>
<ResourceDictionary>
<BooleanNegationConverter x:Key="BooleanNegationConverterKey" />
</ResourceDictionary>
</UserControl.Resources>
Upvotes: 1
Reputation: 128146
You will have to write a converter, i.e. a class that implements the IValueConverter interface. The converter will then be assigned to the Converter property of your binding:
<ComboBox IsEnabled="{Binding Path=CheckBoxIsChecked, Mode=OneWay, Converter={StaticResource MyConverter}}"/>
Upvotes: 1