【发布时间】:2017-10-08 18:37:34
【问题描述】:
WPF .NET 4.6
在下面的代码中,点击菜单项会激活命令并正确显示:
“InkAndGesture 命令已执行”
据我了解,RoutedUICommand 将在可视化树上上下移动。那么 ProgressNoteEditor(ItemsControl 中包含的自定义控件)如何侦听自定义命令并对其执行操作? (ProgressNoteEditor 的实例有很多)???
注意:我需要所有 ProgressNoteEditor 实例来响应,而不仅仅是一个,所以 CommandTarget 没有用。命令只会冒泡吗?
TIA。
我有一个 CustomControl (ProgressNoteEditor),它在 MainWindow 中用作:
<ItemsControl x:Name="ProgressNote" Grid.Column="1" Grid.Row="1" ItemsSource="{Binding WritingLayer.ProgressNote}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<pn:ProgressNoteEditor LineCount="{Binding LineCount}"
Background="{Binding Background}"
Vocabulary="{Binding Vocabulary}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
从主窗口的菜单中,我添加了一个自定义命令:
<MenuItem Header="Ink And Getsures" Command="pn:NotePadCommands.InkAndGesture"/>
代码隐藏:
private void NewProgressNoteView_Loaded(object sender, RoutedEventArgs e)
{
CommandBindings.Add(
new CommandBinding(NotePadCommands.InkAndGesture, NotePadCommands.InkAndGesture_Executed, NotePadCommands.InkAndGesture_CanExecute));
}
目前,CustomCommand 在其自己的类中定义为:
namespace NotePad
{
public static class NotePadCommands
{
// Allow InkCanvas controls to use Gestures with Ink.
private static RoutedUICommand _InkAndGesture;
static NotePadCommands()
{
_InkAndGesture = new RoutedUICommand("Allow Gestures with Ink","InkAndGesture", typeof(NotePadCommands));
}
// Command: InkAndGesture
public static RoutedUICommand InkAndGesture
{
get { return _InkAndGesture; }
}
public static void InkAndGesture_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("InkAndGesture command executed");
}
public static void InkAndGesture_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
}
}
【问题讨论】:
-
如果未设置命令目标 - 它会从具有键盘焦点的元素开始冒泡和隧道化。这可能是您的菜单项,它不能从它隧道到您的 ProgressNoteEditors,因为它们不是菜单项的子项。但是当它冒泡时 - 它总是可以到达您的窗口,因为它是可视树的根。
-
@Evk 嗯.. 所以即使是隧道事件也不会到达 ProgressNoteEditors,因为它们不是菜单的子级?
-
据我了解,这是有道理的。您可以尝试将 CommandTarget 设置为可以通过隧道访问您的编辑器的某个元素(例如 MainWindow 本身)。
标签: wpf custom-controls routed-commands