如何将 CustomControl 绑定到 CustomCommand?

How to bind a CustomControl to a CustomCommand?

WPF.NET 4.6

在下面的代码中,点击菜单项将激活命令并正确显示:

"InkAndGesture command executed"

据我了解,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 在它自己的 class 中定义为:

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;
        }

    }
}

Do commands only bubble up?

A RoutedCommandfocused 元素 up 搜索可视化树以查找具有匹配 CommandBinding 然后为这个特定的 CommandBinding.

执行 Execute 委托

因此 ProgressNoteEditor 元素的 CommandBinding 将不会被发现 MenuItem 调用命令,因为它不是 MenuItem 的可视祖先。