Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Do not show Context menu when ListView is empty

I have a ContextMenu bind to ListView, but I don't want to be the menu shown when the ListView is empty. I tried direct binding to element, tried binding using FindAncestor, but none of these works and the menu is always shown when I click right mouse button in the ListView. What would be the correct binding?

<Grid>
<ListView x:Name="loginListView" ItemsSource="{Binding Logins}">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="140" Header="Login" DisplayMemberBinding="{Binding Login}"/>
            <GridViewColumn Width="140" Header="Password" DisplayMemberBinding="{Binding Password}" />
        </GridView>
    </ListView.View>

    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem 
                Header="Delete login" 
                Visibility="{Binding ElementName=loginListView, Path=Items.Count, Converter={StaticResource VisibilityConverter}}"/>
        </ContextMenu>
    </ListView.ContextMenu>
</ListView>

public class visibilityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((int)value > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }                
}

Thanks in advance!

like image 841
George Hx Avatar asked Jan 22 '23 16:01

George Hx


2 Answers

Use the ContextMenuService.IsEnabled property to prevent the ContextMenu from being shown. Something like:

<ListView x:Name="loginListView" ItemsSource="{Binding Logins}"
    ContextMenuService.IsEnabled="{Binding ElementName=loginListView,
        Path=Items.Count, Converter={StaticResource VisibilityConverter}}">

using the converter that returns True or False.

Since the binding is now on the ListView itself, you could also use a Binding with a RelativeSource of Self instead of having to use ElementName, or you could bind directly to the DataContext by setting the path to Logins.Count (assuming Logins has its own Count property).

like image 185
Quartermeister Avatar answered Feb 02 '23 01:02

Quartermeister


The easiest way to do this is to listen to the ListView's ContextMenuOpening event. You can then perform whatever logic you want and cancel the menu from opening.

like image 22
rossisdead Avatar answered Feb 02 '23 03:02

rossisdead