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>
在MainWindow的菜单中,我添加了一个自定义命令:
<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;
}
}
}
答案 0 :(得分:1)
命令只会冒泡吗?
RoutedCommand
从焦点元素和向上搜索可视树,找到匹配CommandBinding
的元素,然后执行{ {1}}代表此特定Execute
。
因此CommandBinding
元素的CommandBinding
找不到ProgressNoteEditor
调用命令,因为它不是MenuItem
的视觉祖先。