RoutedCommands使用隧道而不是冒泡 [英] RoutedCommands that use tunneling instead of bubbling

查看:278
本文介绍了RoutedCommands使用隧道而不是冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义控件( MyControl )暴露了一个自定义命令。我想父窗口能够调用这个命令,所有 MyControls 应该对它做出反应。

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.

我已将命令添加到 MyControl CommandBindings 它还提供总是返回真的 CanExecute 回调。

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

我的问题是调用此命令的菜单项永远不会启用。我假设这是因为菜单在视觉树中的 MyControls 之上,但是说实话我有点模糊如何 RoutedUICommand

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?

推荐答案

是的,关键是你的自定义命令的CommandBinding在视觉树中的菜单项。从 msdn

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


当RoutedCommand上的CanExecute方法被调用时,在命令目标上引发PreviewCanExecute事件。如果事件未被处理,则抛出CanExecute事件。如果命令目标具有该命令的CommandBinding,则调用该CommandBinding的CanExecute处理程序。 如果命令目标没有命令的CommandBinding,CanExecute事件会弹出元素树,搜索具有与该命令相关联的CommandBinding的元素。

一个关于在此链接

无论如何你可以使用CommandTarget命令从你的菜单项,如

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).

这篇关于RoutedCommands使用隧道而不是冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆