简体   繁体   中英

Unchecking item in a context menu

I currently have a ContextMenu in C# WPF, displaying a MenuItem. This ContextMenu is then utilized by a TrayIcon.

// menu initialization
private static System.Windows.Controls.ContextMenu trayMenu = new System.Windows.Controls.ContextMenu();

// menu item initialization
private static System.Windows.Controls.MenuItem displayOnScreenControls = new System.Windows.Controls.MenuItem();
displayOnScreenControls.Header = "Display presenter controls";
displayOnScreenControls.IsCheckable = true;
displayOnScreenControls.Checked += new RoutedEventHandler(displayOnScreenControls_Checked);
displayOnScreenControls.Unchecked += new RoutedEventHandler(displayOnScreenControls_Unchecked);

// add icons to the tray menu
trayMenu.Items.Add(displayOnScreenControls);

The "displayOnScreenControls" item is checkable. When the user has this option checked and certain conditions are met, a control window will appear.

If the user choses to close this window, this signals they no longer want the control window open. To maintain consistency, I need to uncheck the "displayOnScreenControls" menu item -- otherwise the item will be checked but the window will not be open (which will be confusing for the user if they want to reenable the window, etc).

Any idea on how to handle this? I need to essentially uncheck the menuitem. I could deconstruct the menu and reconstruct it, but that seems like a waste of time.

As always, thanks in advance for any assistance.

So you just want to programmatically uncheck the menu item when your Window is closed? All you need to do is set IsChecked .

displayOnScreenControls.IsChecked = false;

Put that in your Window.Closed event handler and you should be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM