如何:创建 RoutedCommand

更新:2007 年 11 月

此示例通过创建一个 ExecutedRoutedEventHandler 和一个 CanExecuteRoutedEventHandler 并将它们附加到 CommandBinding,演示如何创建自定义 RoutedCommand 以及如何实现该自定义命令。 有关设置命令的更多信息,请参见命令概述

示例

创建 RoutedCommand 的第一步是定义并实例化该命令。

public static RoutedCommand CustomRoutedCommand = new RoutedCommand();

为了在应用程序中使用该命令,必须创建定义该命令的行为的事件处理程序

private void ExecutedCustomCommand(object sender,
    ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Custom Command Executed");
}
// CanExecuteRoutedEventHandler that only returns true if
// the source is a control.
private void CanExecuteCustomCommand(object sender, 
    CanExecuteRoutedEventArgs e)
{
    Control target = e.Source as Control;

    if(target != null)
    {
        e.CanExecute = true;
    }
    else
    {
        e.CanExecute = false;
    }
}

接下来,创建一个 CommandBinding,它将该命令与事件处理程序关联。在指定的对象上创建 CommandBinding。 此对象定义元素树中 CommandBinding 的范围

<Window x:Class="SDKSamples.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:SDKSamples"
    Height="600" Width="800"
    >
  <Window.CommandBindings>
    <CommandBinding Command="{x:Static custom:Window1.CustomRoutedCommand}"
                    Executed="ExecutedCustomCommand"
                    CanExecute="CanExecuteCustomCommand" />
  </Window.CommandBindings>
CommandBinding customCommandBinding = new CommandBinding(
    CustomRoutedCommand, ExecutedCustomCommand, CanExecuteCustomCommand);

// attach CommandBinding to root window
this.CommandBindings.Add(customCommandBinding);

最后一步是调用该命令。 调用命令的一种方式是将该命令与某个 ICommandSource(例如 Button)关联。

<StackPanel>
  <Button Command="{x:Static custom:Window1.CustomRoutedCommand}"
          Content="CustomRoutedCommand"/>
</StackPanel>
// create the ui
StackPanel CustomCommandStackPanel = new StackPanel();
Button CustomCommandButton = new Button();
CustomCommandStackPanel.Children.Add(CustomCommandButton);

CustomCommandButton.Command = CustomRoutedCommand;

单击该 Button 时,将调用自定义 RoutedCommand 上的 Execute 方法。 RoutedCommand 将引发 PreviewExecutedExecuted 路由事件。 这些事件会遍历元素树,以查找该特定命令的 CommandBinding。 如果找到 CommandBinding,则调用与 CommandBinding 关联的 ExecutedRoutedEventHandler

请参见

概念

命令概述

参考

RoutedCommand