views:

1154

answers:

1

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

+2  A: 

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;
ChrisF
wouldn't Visibility.Collapsed be better?
Botz3000
Thanks - I've updated the answer
ChrisF