RoutedCommands that use tunneling instead of bubbling

可紊 提交于 2020-01-14 16:34:38

问题


I have a custom control (MyControl) that exposes a custom command. I want the parent Window to be able to invoke this command, and all MyControls should react to it.

I have added the command to MyControl's CommandBindings collection, which also provides a CanExecute callback that always returns true.

My problem is that a menu item that invokes this command never gets enabled. I'm presuming this is because the menu is above the MyControls in the visual tree, but to be honest I'm a little fuzzy on how RoutedUICommand's scope works exactly.

Can someone clarify what I'm doing wrong, or if this is even possible?


回答1:


Yes, the point is that the CommandBinding for your custom command is at a lower that your menu item in the visual tree. From msdn

When the CanExecute method on a RoutedCommand is called, the PreviewCanExecute event is raised on the command target. If the event is not handled, the CanExecute event is raised. If the command target has a CommandBinding for the command, the CanExecute handler for that CommandBinding is called. If the command target does not have a CommandBinding for the command, the CanExecute event bubbles up the element tree searching for an element that has a CommandBinding associated with the command.

A very good article about commands in at this link.

Anyway you can use CommandTarget the command from your menu item such as

<MenuItem Header="Click me"  Command="local:CommandClass.MyCustomCommand" CommandTarget="{Binding ElementName=myCustomCtrl}" />

In this way a particular command source (the menu item) directs the command to the specific target (instance of the custom control).




回答2:


I guess commands are the wrong mean here.

Commands are used to bundle different command trigger sources to one single command handler. So the command is triggered from different controls, menus, ... but the same command handler is called.

Events are sort of opposit. One source can trigger multiple event handlers.

In your special case I would prefer an event and the the controls below your UI tree would than listen to the tunneling events or the bubbling events.



来源:https://stackoverflow.com/questions/12726266/routedcommands-that-use-tunneling-instead-of-bubbling

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