Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind two elements' Visibility to one property

Tags:

wpf

I have two Menu Item elements - "Undelete" and "Delete" who have complementary visibility: when one is shown, the other one is hidden.

In the code of the ViewModel I have a dependency property FilesSelectedCanBeUndeleted defined as below:

private bool _filesSelectedCanBeUndeleted;
public bool FilesSelectedCanBeUndeleted
{
    get
    {
        return _filesSelectedCanBeUndeleted;
    }
    set
    {
        _filesSelectedCanBeUndeleted = value;
        OnPropertyChanged("FilesSelectedCanBeUndeleted");
    }
}

the XAML for the Undelete button looks like below:

<MenuItem Header="Undelete" Command="{Binding UndeleteCommand }" 
Visibility="{Binding Path=FilesSelectedCanBeUndeleted, 
Converter={StaticResource BoolToVisConverter}}" >

As you can see the Visibility of the Undelete is bind to the FilesSelectedCanBeUndeleted property ( with the help of a BooleanToVisibilityConveter).

Now my question is, how can I write the XAML to bind the Visibility of the Delete button to the "NOT" value of the FilesSelectedCanBeUndeleted property?

Thanks,

like image 680
sean717 Avatar asked Jan 20 '23 23:01

sean717


2 Answers

Here is an example of a custom IValueConverter, that allows you to reverse the visibility logic. Basically, one MenuItem will be visible when your view-model property is true, and the other would be collapsed.

So you'd need to define two instances of the converter like so:

<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<local:BooleanToVisibilityConverter x:Key="ReversedBooleanToVisibilityConverter" IsReversed="true" />
like image 66
CodeNaked Avatar answered Mar 19 '23 23:03

CodeNaked


You can use apply the datatrigger to you menuitem to avoid another property in your viemodel like this -

        <MenuItem Header="Delete"
                  Command="{Binding DeleteCommand }">
            <MenuItem.Style>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Visibility" Value="Visible" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding FilesSelectedCanBeUndeleted}" Value="False">
                            <Setter Property="Visibility"
                                    Value="Collapsed" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </MenuItem.Style>
        </MenuItem>
like image 30
Rohit Vats Avatar answered Mar 20 '23 00:03

Rohit Vats