Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Hiding ContextMenu when empty

I have a context menu that gets menu items through databinding (I'm using the MVVM pattern):

<ContextMenu ItemsSource="{Binding Path=ContextMenuItems}" />

This works fine. However, in the cases when there are no menu items to show, I don't want the context menu to show up at all. Is there a way to accomplish this? Some kind of XAML trigger maybe?

I've tried catching the Opened event och closing the context menu when there are no children. This works but the context menu still flashes by...

like image 782
haagel Avatar asked Nov 16 '10 09:11

haagel


2 Answers

Maybe bind to your menu items collections count property and use a converter to set the context menu's visibility.

 <ContextMenu ItemsSource="{Binding Path=ContextMenuItems}"
              Visibility="{Binding Path=ContextMenuItems.Count,Converter={StaticResource zeroToHiddenConverter}}">

public  class ZeroToHiddenConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    {
        int count = (int) value;

        if (count == 0) 
        {
            return Visibility.Hidden;
        }
        else
        {
            return Visibility.Visible;
        }
    }
like image 98
ThomasAndersson Avatar answered Nov 16 '22 17:11

ThomasAndersson


You can define an implicit style:

<Style TargetType="{x:Type ContextMenu}">
    <Style.Triggers>
        <Trigger Property="HasItems" Value="False">
            <Setter Property="Visibility" Value="Collapsed" />
        </Trigger>
    </Style.Triggers>
</Style>

This should work for all your context menus at once.

like image 25
pbalaga Avatar answered Nov 16 '22 17:11

pbalaga