Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Visibility based on multiple properties

Tags:

mvvm

wpf

I have a Canvas that I want to hide or show based off of 2 dependency properties:

IsPropA
IsPropB

If either of these are true I want the Canvas to display. If both are false I want the Canvas to be hidden.

I know how I can do it with just 1 property. But I'm unsure of how to do it with multiple properties.

<Canvas Grid.Row="2" x:Name="sesimicTeam" Visibility="{Binding IsPropA}">
like image 277
webdad3 Avatar asked Jan 16 '14 14:01

webdad3


2 Answers

you could use MultiDataTrigger

<Canvas Grid.Row="2" x:Name="sesimicTeam">
    <Canvas.Style>
        <Style>
            <Setter Property="Control.Visibility" Value="Visible" />
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding Path=IsPropA}" Value="false" />
                        <Condition Binding="{Binding Path=IsPropB}" Value="false" />
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Control.Visibility" Value="Hidden" />
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>
    </Canvas.Style>
</Canvas>

now it will show your Canvas if one of your Properties is true

like image 109
WiiMaxx Avatar answered Nov 07 '22 21:11

WiiMaxx


You can do this with a IMultiValueConverter. That interface accepts any number of bindings and returns a single value.

XAML

<Canvas>
    <Canvas.Resources>
        <converter:BooleanToVisibilityMultiConverter x:Key="BooleanToVisibilityMultiConverter" />
    </Canvas.Resources>
    <Canvas.Visibility>
        <MultiBinding Converter="{StaticResource BooleanToVisibilityMultiConverter}">
            <Binding Path="IsPropA" />
            <Binding Path="IsPropB" />
        </MultiBinding>
    </Canvas.Visibility>
</Canvas>

C#

public class BooleanToVisibilityMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.OfType<bool>().Any(b => b) ? Visibility.Visible : Visibility.Hidden;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
like image 30
Kevin Kalitowski Avatar answered Nov 07 '22 21:11

Kevin Kalitowski