Question

I need to programatically show/hide a MenuItem, what would be the best way to do this?

Was it helpful?

Solution

Well, to add a MenuItem you'll need something along these lines:

var menuItem = new MenuItem() { Header = "Menu Name", Name = "Identifier", IsCheckable = true, IsChecked = visible };
menuItem.Click += new RoutedEventHandler(contextMenu_onClick);
int position = contextMenu.Items.Add(menuItem);

(but you've probably already got this).

You will need some way of tying the menu item to the property - but without seeing your application I can't really suggest the best way. There's the Tag property which stores an object; the Uid property which stores a string; the Name property which also stores a string.

While:

menuItem.Visibility = Visibility.Visible;

and

menuItem.Visibility = Visibility.Collapsed;

should toggle the visibility of the item.

EDIT: Using Collapsed will hide the menu item and not reserve space in the menu - you don't really want blank spaces in a context menu. (thanks to Botz3000 for this)

Then in your code where the property value is changed you'll to find the menu item you wish to show/hide using the linkage I described above. Once you have the item you can switch it's value:

menuItem.Visibility = menuItem.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;

OTHER TIPS

Are you sure you want to hide the MenuItem? It is more common to disable it, using WPF's commanding framework:

<MenuItem Header="_MenuName" Command="{x:Static local:MyCommands.SomeCommand}" />

...

<!-- In the menu item or any of its ancestors: -->
<SomeControl.CommandBindings>
    <CommandBinding Command="{x:Static local:MyCommands.SomeCommand}" Executed="Save_Executed" CanExecute="Save_CanExecture" />
</SomeControl.CommandBindings>

WPF will use the bool result of Save_CanExecute to determine whether the MenuItem's command can currently execute, and enable/disable the MenuItem accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top