WPF Visiblity Binding to Boolean Expression with multiple Variables

There is no && operator defined in XAML but you could bind to several properties and use an IMultiValueConverter:

<Image>
    <Image.Visibility>
        <MultiBinding Converter="{StaticResource YourMultiConverter}">
            <Binding Path="Boolean1" />
            <Binding Path="Boolean2" />
        </MultiBinding>
    </Image.Visibility>
</Image>

public class YourMultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool a = (bool)values[0];
        bool b = (bool)values[1];

        return a && b ? Visibility.Visible : Visibility.Collapsed;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Or you could use an Image style with conditions:

<Image>
    <Image.Style>
        <Style TargetType="Image">
            <Setter Property="Visibility" Value="Collapsed" />
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding Boolean1}" Value="True" />
                        <Condition Binding="{Binding Boolean2}" Value="True" />
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Visibility" Value="Visible" />
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

mm8 has provided the correct answer however a slight improvement would be this

public class LogicalAndConverter : IMultiValueConverter
{
    public IValueConverter FinalConverter{get;set;}

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool rtn = values.All(v=>(bool)v);

        if(FinalConverter==null)    
            return rtn;
        else
            return FinalConverter.Convert(rtn,targetType,parameter,culture);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

this then allows you do use different converters with out rewriting the multiconverter

<local:LogicalAndConverter x:Key="LogicalAndConverter ">
    <local:LogicalAndConverter.FinalConverter>
        <BooleanToVisibilityConverter />
    </local:LogicalAndConverter.FinalConverter>
</local:LogicalAndConverter>

Tags:

Wpf

Xaml