共用方式為


HOW TO:建立 RoutedCommand

更新:2007 年 11 月

本範例示範如何建立自訂 RoutedCommand,以及如何透過建立 ExecutedRoutedEventHandlerCanExecuteRoutedEventHandler 並將它們附加到 CommandBinding 的方式,實作該自訂命令。如需使用命令的詳細資訊,請參閱命令概觀

範例

建立 RoutedCommand 的第一個步驟是定義命令並將它具現化。

public static RoutedCommand CustomRoutedCommand = new RoutedCommand();

您必須建立定義命令功能的事件處理常式 (Event Handler),才能在應用程式中使用該命令。

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

最後一個步驟是叫用 (Invoke) 命令。叫用命令的其中一種方法是讓命令與 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;

按一下按鈕時,便會呼叫自訂 RoutedCommand 上的 Execute 方法。RoutedCommand 會引發 PreviewExecutedExecuted 路由事件。這些事件會在項目樹狀結構中周遊,以尋找此特定命令的 CommandBinding。如果找到 CommandBinding,便會呼叫與 CommandBinding 相關聯的 ExecutedRoutedEventHandler

請參閱

概念

命令概觀

參考

RoutedCommand