hardcodet / wpf-notifyicon

NotifyIcon (aka system tray icon or taskbar icon) for the WPF platform
MIT License
830 stars 130 forks source link

MenuItems in ContextMenu on Tray Icon Using Commands Always Disabled #23

Closed uyaem closed 2 years ago

uyaem commented 4 years ago

CS

public static RoutedCommand ChooseFolderCommand = new RoutedCommand();

private void ChooseFolderCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
    // ...
}

XAML

<Window.CommandBindings>
    <CommandBinding Command="local:MainWindow.ChooseFolderCommand" Executed="ChooseFolderCommandExecuted" />
</Window.CommandBindings>

<tb:TaskbarIcon x:Name="trayMenu" IconSource="/Assets/quill-64.ico">
    <tb:TaskbarIcon.ContextMenu>
        <ContextMenu Opened="ContextMenu_Opened">
            <MenuItem Header="Choose folder" Command="local:MainWindow.ChooseFolderCommand" />
        </ContextMenu>
    </tb:TaskbarIcon.ContextMenu>
</tb:TaskbarIcon>

Noteworthy

maxpavlov commented 2 years ago

Since this is a major drawback affecting many who follow the standard command approach for context menus, could you please elaborate on how you managed to resolve this via CanExecute by providing the example? Would be really appreciated.

maxpavlov commented 2 years ago

Oh, I see, you @uyaem probably meant that in order to troubleshoot the issue you've attached the CanExecute method, but it didn't yield any results nonetheless, as it never gets called from what I see.

maxpavlov commented 2 years ago

Just for anyone who comes across this - I was only able to get this to work using the trivial (non routed commands) from the example application in the repository. I had to inject the IoC into the command handler via a parameter allowing the commands to be kind of self-sufficient, otherwise, as per example, they can only react within the Visual Tree which is pretty useless. So if you need commands to work in the Tray Icon context menu - use the approach from here: https://github.com/hardcodet/wpf-notifyicon/tree/master/src/NotifyIconWpf.Sample.ShowCases/Tutorials/04%20-%20ContextMenus

Lakritzator commented 2 years ago

I'm horrible at WPF, commands and "bubbling" events... I have seen many weird things, and usually just take the quirks and their solutions for granted...

I believe the context menu is completely separate from the normal visual tree (it's a popup with it's own root), and thus also has issues with events, commands and even styles.

I'm not sure if this can be made better, but the mentioned tutorial seems to help.

I also found this here: https://stackoverflow.com/questions/59698021/wpf-context-menu-commands-not-setting-isenabled-properly

Closing this, as there is a "solution" and from my point of view we currently have way more pressing things then to fix issues with the way WPF works.