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...
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With