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();

      

+1


source to share


3 answers


From the top of my head, I would suggest that you have to add a CommandBinding to the menu or systray for your command to be processed. Although I think that if it were, it would be enabled by default.



+3


source


Yes, I've seen it. Sometimes you need to tell the WPF CommandManager to rerun the CanExecute methods. Try calling this after loading the ContextMenu:CommandManager.InvalidateQuerySuggested();



+2


source


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);
    }

      

0


source







All Articles