Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF hide MenuItem on ContextMenu based on object property

Tags:

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

like image 229
Sara Chipps Avatar asked May 08 '09 23:05

Sara Chipps


1 Answers

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;
like image 112
ChrisF Avatar answered Oct 20 '22 00:10

ChrisF