I have a WPF xaml file describing a section of a GUI and I'd like the enabling/disabling of a particular control to be dependent on two others. The code looks something like this at the moment:
<ComboBox Name="MyComboBox"
IsEnabled="{Binding ElementName=SomeCheckBox, Path=IsChecked}"/>
But I'd like it to be dependant on another checkbox as well so something like:
<ComboBox Name="MyComboBox"
IsEnabled="{Binding ElementName=SomeCheckBox&AnotherCheckbox, Path=IsChecked}"/>
What's the best way to go about that? I can't help feeling I'm missing something obvious or going about this the wrong way?
You can use a MultiBinding
with a converter which implements IMultiValueConverter
.
Just to give an answer you can (almost) copy&paste:
Static resource needed:
<converterNamespace:BooleanAndConverter x:Key="booleanAndConverter" />
The ComboBox:
<ComboBox Name="MyComboBox">
<ComboBox.IsEnabled>
<MultiBinding Converter="{StaticResource booleanAndConverter}">
<Binding ElementName="SomeCheckBox" Path="IsChecked" />
<Binding ElementName="AnotherCheckbox" Path="IsChecked" />
</MultiBinding>
</ComboBox.IsEnabled>
</ComboBox>
The code for the converter:
namespace ConverterNamespace
{
public class BooleanAndConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
foreach (object value in values)
{
if ((value is bool) && (bool)value == false)
{
return false;
}
}
return true;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("BooleanAndConverter is a OneWay converter.");
}
}
}