CommandBinding in Window doesn't catch execution of command from ContextMenu

你离开我真会死。 提交于 2019-12-12 12:11:17

问题


A quite simple and straightforward example.

I have a window. It has CommandBindings set to catch a RoutedUICommand execution.

<Window
   ...
   >
   <Window.CommandBinding>
       <CommandBinding 
           Command="{x:Static local:Commands.Command1}"  
           Executed="OnCommand1Executed" 
           CanExecute="OnCanCommand1Execute" 
           />
   </Window.CommandBinding>
</Window>

There's a UserControl hosted in the window, inside of which a ContextMenu is declared. A ContextMenu item has the Command property assigned to the same RoutedUICommand.

<ContextMenu>
    <MenuItem Command="{x:Static local:Commands.Command1}" />
</ContextMenu>

But the menu item remains inactive (== disabled). Somehow command execution doesn't go up to the window. Maybe it's because ContextMenu is inside of a popup?

Everything works properly if I add needed CommandBinding into the ContextMenu.CommandBindings collection. But that's a terrible option to not have a place for a single 'global' CommandBinding.

How can I solve the problem in the best way?

UPD: Turns out it's not that bad. The Commands aren't bound only at the first time user opens the menu. If it's closed and reopened everything's fine. Still, it seems to be not desirable and a quite weird behavior.


回答1:


Does this still occur if you add Focus(); right after InitializeComponent(); in the windows constructor?

This sounds like WPF is having an issue finding the visual tree from the context menu. Setting the focus to the main window might fix it.




回答2:


How we can handle this issue in a user control? It seems that focus doesn't work in that context

Update : I found the solution here How to set CommandTarget for MenuItem inside a ContextMenu?

Seems that it's related to CommandTarget

<MenuItem x:Name="mnuProperties" Header="_Properties"
          Command="{x:Static localcommands:TaskCommands.ViewTaskProperties}"
          CommandTarget="{Binding PlacementTarget,
          RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu}}}"/>


来源:https://stackoverflow.com/questions/911904/commandbinding-in-window-doesnt-catch-execution-of-command-from-contextmenu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!