共用方式為


HOW TO:將命令與沒有命令支援的控制項連結

更新:2007 年 11 月

下列範例顯示如何將 RoutedCommand 與沒有命令內建支援的 Control 連結。如需會將命令與多個來源連結的完整範例,請參閱範例:建立自訂 RoutedCommand 範例

範例

Windows Presentation Foundation (WPF) 提供應用程式開發人員經常會遇到的通用命令程式庫。組成命令程式庫的類別有:ApplicationCommandsComponentCommandsNavigationCommandsMediaCommandsEditingCommands

構成這些類別的靜態 RoutedCommand 物件不提供命令邏輯。命令的邏輯是與具有 CommandBinding 的命令相關聯。WPF 中有許多控制項,對命令程式庫中的某些命令具有內建支援。舉例來說,TextBox 支援許多應用程式編輯命令,例如 PasteCopyCutRedoUndo。應用程式開發人員不需要特別做什麼,就可以讓這些命令與這些控制項一起運作。如果執行命令時 TextBox 是命令目標,就會使用內建在控制項內的 CommandBinding 處理命令。

下列範例顯示如何使用 Button 做為 Open 命令的命令來源。CommandBinding 的建立,會將指定的 CanExecuteRoutedEventHandlerCanExecuteRoutedEventHandlerRoutedCommand 建立關聯。

首先會建立命令來源。Button 是用來做為命令來源。

<Button Command="ApplicationCommands.Open" Name="MyButton"
        Height="50" Width="200">
  Open (KeyBindings: Ctrl+R, Ctrl+0)
</Button>
// Button used to invoke the command
Button CommandButton = new Button();
CommandButton.Command = ApplicationCommands.Open;
CommandButton.Content = "Open (KeyBindings: Ctrl-R, Ctrl-0)";
MainStackPanel.Children.Add(CommandButton);

接著會建立 ExecutedRoutedEventHandlerCanExecuteRoutedEventHandlerExecutedRoutedEventHandler 會直接開啟 MessageBox 以表示命令已執行。CanExecuteRoutedEventHandler 會將 CanExecute 屬性設為 true。通常,CanExecute 處理常式會執行更健全的檢查,以查看命令是否可以在目前命令目標上執行。

Private Sub OpenCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
    Dim command, targetobj As String
    command = CType(e.Command, RoutedCommand).Name
    targetobj = CType(sender, FrameworkElement).Name
    MessageBox.Show("The " + command + " command has been invoked on target object " + targetobj)
End Sub
Private Sub OpenCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
    e.CanExecute = True
End Sub

void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
    String command, targetobj;
    command = ((RoutedCommand)e.Command).Name;
    targetobj = ((FrameworkElement)target).Name;
    MessageBox.Show("The " + command +  " command has been invoked on target object " + targetobj);
}
void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
}

最後會在應用程式的根 Window 上,建立會將路由事件處理常式與 Open 命令建立關聯的 CommandBinding

<Window.CommandBindings>
  <CommandBinding Command="ApplicationCommands.Open"
                  Executed="OpenCmdExecuted"
                  CanExecute="OpenCmdCanExecute"/>
</Window.CommandBindings>
// Creating CommandBinding and attaching an Executed and CanExecute handler
CommandBinding OpenCmdBinding = new CommandBinding(
    ApplicationCommands.Open,
    OpenCmdExecuted,
    OpenCmdCanExecute);

this.CommandBindings.Add(OpenCmdBinding);

請參閱

工作

HOW TO:將命令與含有命令支援的控制項連結

概念

命令概觀