Systray context menu - why aren't my commands enabled?
I am creating a WPF application and have a system tray icon with a context menu. For menu items, I want to use WPF commands, but when I assign them, they are always greyed out, even if the same commands are enabled elsewhere.
MenuItem menuItem = new MenuItem();
menuItem.Header = "Exit";
menuItem.Command = CustomCommands.ExitApplication;
Systray.AddMenuItem(menuItem);
It works great when I assign click events and I tried to create a CanExecute method for the command that always sets CanExecute to true, but that doesn't help either. Does anyone understand why the menu items are disabled?
Update. As suggested, I added a command binding to the context menu. This made it work, but only after you clicked on the menu, i.e. at first the menu items are inactive, but as soon as you click anywhere in the menu, the options will become enabled.
To solve this problem, I called the following, after adding the menu items to the context menu:
CommandManager.InvalidateRequerySuggested();
source to share
I had a similar problem. I feel like this solution was a bit of a hack, but I really couldn't get around this issue. I am using a custom implementation of DelegateCommand and also ebabling / disabling buttons and menu items, excluding items in context menus. So what I did was handle the ContextMenuOpening event, then store the items in the temp variable, call the Clear method on the ContextMenu, and re-add the items right after. Works like a charm, but as I said, it feels "hacked". It goes something like this:
private void ContextMenu_ContextMenuOpening (object sender, System.ComponentModel.CancelEventArgs e)
{
// HACK: For some reason items need to be removed and added back so that the command enablement requery works.
var menu = sender as ContextMenu;
if (menu == null) return;
var menuItems = menu.Items.ToArray();
menu.Items.Clear();
foreach (var menuItem in menuItems)
menu.Items.Add(menuItem);
}
source to share