命令概觀Commanding Overview

命令是處理比裝置輸入更接近語意層級的 Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 中的輸入機制。Commanding is an input mechanism in Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) which provides input handling at a more semantic level than device input. 命令範例包含許多應用程式中都有的 [複製]、[剪下] 和 [貼上] 作業。Examples of commands are the Copy, Cut, and Paste operations found on many applications.

本概觀會定義 WPFWPF 中有哪些命令、哪些類別屬於命令模型,以及如何在應用程式中使用及建立命令。This overview defines what commands are in WPFWPF, which classes are part of the commanding model, and how to use and create commands in your applications.

本主題包含下列各節:This topic contains the following sections:

命令是什麼?What Are Commands?

命令有多種用途。Commands have several purposes. 第一個用途是要分隔語意和從執行命令的邏輯叫用命令的物件。The first purpose is to separate the semantics and the object that invokes a command from the logic that executes the command. 這可讓多個不同的來源叫用相同的命令邏輯,並可針對不同的目標自訂命令邏輯。This allows for multiple and disparate sources to invoke the same command logic, and it allows the command logic to be customized for different targets. 例如,許多應用程式中都有的 [複製]、[剪下] 和 [貼上] 等編輯作業;如果使用命令實作,即可使用不同的使用者動作叫用。For example, the editing operations Copy, Cut, and Paste, which are found in many applications, can be invoked by using different user actions if they are implemented by using commands. 應用程式可能會讓使用者按一下按鈕、選擇功能表中的項目,或使用 CTRL+X 等按鍵組合,剪下選取的物件或文字。An application might allow a user to cut selected objects or text by either clicking a button, choosing an item in a menu, or using a key combination, such as CTRL+X. 您可以使用命令將每一種使用者動作類型繫結至相同的邏輯。By using commands, you can bind each type of user action to the same logic.

命令的另一項用途是指出是否有動作可用。Another purpose of commands is to indicate whether an action is available. 若要繼續剪下物件或文字的範例,只有選取項目時動作才有意義。To continue the example of cutting an object or text, the action only makes sense when something is selected. 如果使用者嘗試剪下物件或文字,但未選取任何項目,不會有任何事發生。If a user tries to cut an object or text without having anything selected, nothing would happen. 為向使用者指出這個狀況,許多應用程式會停用按鈕和功能表項目,讓使用者知道是否能執行某動作。To indicate this to the user, many applications disable buttons and menu items so that the user knows whether it is possible to perform an action. 命令可以透過實作 CanExecute 方法來指出一個動作是否可能執行。A command can indicate whether an action is possible by implementing the CanExecute method. 按鈕可以訂閱 CanExecuteChanged 事件,如果 CanExecute 傳回 false 則會停用,如果 CanExecute 傳回 true 則會啟用。A button can subscribe to the CanExecuteChanged event and be disabled if CanExecute returns false or be enabled if CanExecute returns true.

命令語意在不同的應用程式和類別中可以一致,但動作邏輯專屬於於其上執行動作的特定物件。The semantics of a command can be consistent across applications and classes, but the logic of the action is specific to the particular object acted upon. 按鍵組合 CTRL+X 在文字類別、映像類別及網頁瀏覽器中叫用 [剪下] 命令,但執行 [剪下] 作業的實際邏輯是由執行剪下動作的應用程式所定義。The key combination CTRL+X invokes the Cut command in text classes, image classes, and Web browsers, but the actual logic for performing the Cut operation is defined by the application that performs the cut. RoutedCommand 可讓用戶端實作邏輯。A RoutedCommand enables clients to implement the logic. 文字物件可能會將選取的文字剪入剪貼簿,而映像物件可能會剪下選取的映像。A text object may cut the selected text into the clipboard, while an image object may cut the selected image. 當應用程式處理 Executed 事件時,可以存取命令目標,並根據目標類型採取適當的動作。When an application handles the Executed event, it has access to the target of the command and can take appropriate action depending on the target's type.

WPF 中的簡單命令範例Simple Command Example in WPF

WPFWPF 中使用命令最簡單的方式,是從命令程式庫類別之一使用預先定義的 RoutedCommand、使用有可處理命令之原生支援的控制項,以及使用有可叫用命令之原生支援的控制項。The simplest way to use a command in WPFWPF is to use a predefined RoutedCommand from one of the command library classes; use a control that has native support for handling the command; and use a control that has native support for invoking a command. Paste 命令是在 ApplicationCommands 類別中的其中一個預先定義命令。The Paste command is one of the predefined commands in the ApplicationCommands class. TextBox 控制項具有內建邏輯來處理 Paste 命令。The TextBox control has built in logic for handling the Paste command. MenuItem 類別具有叫用命令的原生支援。And the MenuItem class has native support for invoking commands.

下列範例示範如何設定 MenuItem,以便其在按一下時叫用 Paste 上的 TextBox 命令,假設 TextBox 具有鍵盤焦點。The following example shows how to set up a MenuItem so that when it is clicked it will invoke the Paste command on a TextBox, assuming the TextBox has keyboard focus.

<StackPanel>
  <Menu>
    <MenuItem Command="ApplicationCommands.Paste" />
  </Menu>
  <TextBox />
</StackPanel>
  // Creating the UI objects
  StackPanel mainStackPanel = new StackPanel();
  TextBox pasteTextBox = new TextBox();
  Menu stackPanelMenu = new Menu();
  MenuItem pasteMenuItem = new MenuItem();
 
  // Adding objects to the panel and the menu
  stackPanelMenu.Items.Add(pasteMenuItem);
  mainStackPanel.Children.Add(stackPanelMenu);
  mainStackPanel.Children.Add(pasteTextBox);

  // Setting the command to the Paste command
  pasteMenuItem.Command = ApplicationCommands.Paste;

  // Setting the command target to the TextBox
  pasteMenuItem.CommandTarget = pasteTextBox;
' Creating the UI objects
Dim mainStackPanel As New StackPanel()
Dim pasteTextBox As New TextBox()
Dim stackPanelMenu As New Menu()
Dim pasteMenuItem As New MenuItem()

' Adding objects to the panel and the menu
stackPanelMenu.Items.Add(pasteMenuItem)
mainStackPanel.Children.Add(stackPanelMenu)
mainStackPanel.Children.Add(pasteTextBox)

' Setting the command to the Paste command
pasteMenuItem.Command = ApplicationCommands.Paste

WPF 命令的四個主要概念Four Main Concepts in WPF Commanding

WPFWPF 中的路由命令模型可以分成四個主要概念︰命令、命令來源、命令目標和命令繫結︰The routed command model in WPFWPF can be broken up into four main concepts: the command, the command source, the command target, and the command binding:

  • 「命令」是要執行的動作。The command is the action to be executed.

  • 「命令來源」是叫用命令的物件。The command source is the object which invokes the command.

  • 「命令目標」是在其上執行命令的物件。The command target is the object that the command is being executed on.

  • 「命令繫結」是對應命令邏輯和命令的物件。The command binding is the object which maps the command logic to the command.

在上述範例中,Paste 命令是命令,MenuItem 是命令來源,TextBox 是命令目標,而命令繫結由 TextBox 控制項提供。In the previous example, the Paste command is the command, the MenuItem is the command source, the TextBox is the command target, and the command binding is supplied by the TextBox control. 值得注意的是,CommandBinding 不一定都是由命令目標類別控制項所提供。It is worth noting that it is not always the case that the CommandBinding is supplied by the control that is the command target class. 通常,CommandBinding 必須由應用程式開發人員建立,或 CommandBinding 可能會附加至命令目標的上階。Quite often the CommandBinding must be created by the application developer, or the CommandBinding might be attached to an ancestor of the command target.

命令Commands

WPFWPF 中的命令是藉由實作 ICommand 介面來建立。Commands in WPFWPF are created by implementing the ICommand interface. ICommand 公開兩個方法:ExecuteCanExecute,以及一個事件 CanExecuteChangedICommand exposes two methods, Execute, and CanExecute, and an event, CanExecuteChanged. Execute 執行與命令建立關聯的動作。Execute performs the actions that are associated with the command. CanExecute 判斷命令是否可以在目前命令目標上執行。CanExecute determines whether the command can execute on the current command target. 如果集中命令作業的命令管理員偵測到命令來源的變更可能會使命令繫結已引發但尚未執行的命令失效,則會引發 CanExecuteChangedCanExecuteChanged is raised if the command manager that centralizes the commanding operations detects a change in the command source that might invalidate a command that has been raised but not yet executed by the command binding. WPFWPF 的實作 ICommandRoutedCommand 類別和此概觀焦點所在。The WPFWPF implementation of ICommand is the RoutedCommand class and is the focus of this overview.

WPFWPF 中的輸入主要來源是滑鼠、鍵盤、筆跡和路由的命令。The main sources of input in WPFWPF are the mouse, the keyboard, ink, and routed commands. 更多裝置導向的輸入使用 RoutedEvent 通知應用程式頁面中的物件有輸入事件發生。The more device-oriented inputs use a RoutedEvent to notify objects in an application page that an input event has occurred. RoutedCommand 並無不同。A RoutedCommand is no different. ExecuteCanExecuteRoutedCommand 方法不包含該命令的應用程式邏輯,而是引發路由事件,該事件會在項目樹狀結構中浮動,直到遇到具有 CommandBinding 的物件。The Execute and CanExecute methods of a RoutedCommand do not contain the application logic for the command, but rather they raise routed events that tunnel and bubble through the element tree until they encounter an object with a CommandBinding. CommandBinding 包含這些事件的處理常式,並且是執行命令的處理常式。The CommandBinding contains the handlers for these events and it is the handlers that perform the command. 如需事件在 WPFWPF 中路由的詳細資訊,請參閱路由事件概觀For more information on event routing in WPFWPF, see Routed Events Overview.

Execute 上之 RoutedCommand 方法會引發命令目標上的 PreviewExecutedExecuted 事件。The Execute method on a RoutedCommand raises the PreviewExecuted and the Executed events on the command target. CanExecute 上之 RoutedCommand 方法會引發命令目標上的 CanExecutePreviewCanExecute 事件。The CanExecute method on a RoutedCommand raises the CanExecute and PreviewCanExecute events on the command target. 這些事件會在項目樹狀結構中浮動,直到遇到有該特定命令之 CommandBinding 的物件。These events tunnel and bubble through the element tree until they encounter an object which has a CommandBinding for that particular command.

WPFWPF 提供分散到數個類別中的一組常見路由命令:MediaCommandsApplicationCommandsNavigationCommandsComponentCommandsEditingCommandssupplies a set of common routed commands spread across several classes: MediaCommands, ApplicationCommands, NavigationCommands, ComponentCommands, and EditingCommands. 這些類別只包含 RoutedCommand 物件,不包含命令的實作邏輯。These classes consist only of the RoutedCommand objects and not the implementation logic of the command. 實作邏輯是於其上執行命令之物件的責任。The implementation logic is the responsibility of the object on which the command is being executed on.

命令來源Command Sources

命令來源是叫用命令的物件。A command source is the object which invokes the command. 命令來源的範例包括 MenuItemButtonKeyGestureExamples of command sources are MenuItem, Button, and KeyGesture.

WPFWPF 中的命令來源通常會實作 ICommandSource 介面。Command sources in WPFWPF generally implement the ICommandSource interface.

ICommandSource 會公開三個屬性:CommandCommandTargetCommandParameterICommandSource exposes three properties: Command, CommandTarget, and CommandParameter:

實作 WPFWPFICommandSource 類別是 ButtonBaseMenuItemHyperlinkInputBindingThe WPFWPF classes that implement ICommandSource are ButtonBase, MenuItem, Hyperlink, and InputBinding. 按一下 ButtonBaseMenuItemHyperlink 時會叫用一個命令,並且在與其建立關聯的 InputBinding 執行時,InputGesture 會叫用一個命令。ButtonBase, MenuItem, and Hyperlink invoke a command when they are clicked, and an InputBinding invokes a command when the InputGesture associated with it is performed.

下列範例示範如何將 MenuItem 中的 ContextMenu 用作 Properties 命令的命令來源。The following example shows how to use a MenuItem in a ContextMenu as a command source for the Properties command.

<StackPanel>
  <StackPanel.ContextMenu>
    <ContextMenu>
      <MenuItem Command="ApplicationCommands.Properties" />
    </ContextMenu>
  </StackPanel.ContextMenu>
</StackPanel>
StackPanel cmdSourcePanel = new StackPanel();
ContextMenu cmdSourceContextMenu = new ContextMenu();
MenuItem cmdSourceMenuItem = new MenuItem();

// Add ContextMenu to the StackPanel.
cmdSourcePanel.ContextMenu = cmdSourceContextMenu;
cmdSourcePanel.ContextMenu.Items.Add(cmdSourceMenuItem);

// Associate Command with MenuItem.
cmdSourceMenuItem.Command = ApplicationCommands.Properties;
Dim cmdSourcePanel As New StackPanel()
Dim cmdSourceContextMenu As New ContextMenu()
Dim cmdSourceMenuItem As New MenuItem()

' Add ContextMenu to the StackPanel.
cmdSourcePanel.ContextMenu = cmdSourceContextMenu
cmdSourcePanel.ContextMenu.Items.Add(cmdSourceMenuItem)

' Associate Command with MenuItem.
cmdSourceMenuItem.Command = ApplicationCommands.Properties

一般而言,命令來源會接聽 CanExecuteChanged 事件。Typically, a command source will listen to the CanExecuteChanged event. 此事件會通知命令來源,命令在目前的命令目標上執行的能力可能已變更。This event informs the command source that the ability of the command to execute on the current command target may have changed. 命令來源可以使用 RoutedCommand 方法來查詢 CanExecute 的目前狀態。The command source can query the current status of the RoutedCommand by using the CanExecute method. 如果命令無法執行,則命令來源可以自行停用。The command source can then disable itself if the command cannot execute. 此情況範例就是 MenuItem 在命令無法執行時把自己變成灰色。An example of this is a MenuItem graying itself out when a command cannot execute.

InputGesture 可用作命令來源。An InputGesture can be used as a command source. WPFWPF 中兩種類型的輸入筆勢為 KeyGestureMouseGestureTwo types of input gestures in WPFWPF are the KeyGesture and MouseGesture. 您可以將 KeyGesture 視為鍵盤快速鍵,例如 CTRL+C。You can think of a KeyGesture as a keyboard shortcut, such as CTRL+C. KeyGestureKey 和一組 ModifierKeys 組成。A KeyGesture is comprised of a Key and a set of ModifierKeys. MouseGestureMouseAction 和選擇性的一組 ModifierKeys 組成。A MouseGesture is comprised of a MouseAction and an optional set of ModifierKeys.

為了讓 InputGesture 表現如同命令來源,必須將其與命令建立關聯。In order for an InputGesture to act as a command source, it must be associated with a command. 有幾種方法可達成這個目標。There are a few ways to accomplish this. 其中一種方式是使用 InputBindingOne way is to use an InputBinding.

下列範例會示範如何在 KeyBindingKeyGesture 之間建立 RoutedCommandThe following example shows how to create a KeyBinding between a KeyGesture and a RoutedCommand.

<Window.InputBindings>
  <KeyBinding Key="B"
              Modifiers="Control" 
              Command="ApplicationCommands.Open" />
</Window.InputBindings>
KeyGesture OpenKeyGesture = new KeyGesture(
    Key.B,
    ModifierKeys.Control);

KeyBinding OpenCmdKeybinding = new KeyBinding(
    ApplicationCommands.Open,
    OpenKeyGesture);

this.InputBindings.Add(OpenCmdKeybinding);
Dim OpenKeyGesture As New KeyGesture(Key.B, ModifierKeys.Control)

Dim OpenCmdKeybinding As New KeyBinding(ApplicationCommands.Open, OpenKeyGesture)

Me.InputBindings.Add(OpenCmdKeybinding)

InputGestureRoutedCommand 建立關聯的另一種方法是將 InputGesture 新增至 InputGestureCollection 上的 RoutedCommandAnother way to associate an InputGesture to a RoutedCommand is to add the InputGesture to the InputGestureCollection on the RoutedCommand.

下列範例示範如何將 KeyGesture 新增至 InputGestureCollectionRoutedCommandThe following example shows how to add a KeyGesture to the InputGestureCollection of a RoutedCommand.

KeyGesture OpenCmdKeyGesture = new KeyGesture(
    Key.B,
    ModifierKeys.Control);

ApplicationCommands.Open.InputGestures.Add(OpenCmdKeyGesture);
Dim OpenCmdKeyGesture As New KeyGesture(Key.B, ModifierKeys.Control)

ApplicationCommands.Open.InputGestures.Add(OpenCmdKeyGesture)

CommandBindingCommandBinding

CommandBinding 會將命令與實作此命令的事件處理常式建立關聯。A CommandBinding associates a command with the event handlers that implement the command.

CommandBinding 類別包含 Command 屬性,以及 PreviewExecutedExecutedPreviewCanExecuteCanExecute 事件。The CommandBinding class contains a Command property, and PreviewExecuted, Executed, PreviewCanExecute, and CanExecute events.

Command 是與 CommandBinding 建立關聯的命令。Command is the command that the CommandBinding is being associated with. 附加到 PreviewExecutedExecuted 事件的事件處理常式會實作命令邏輯。The event handlers which are attached to the PreviewExecuted and Executed events implement the command logic. 附加到 PreviewCanExecuteCanExecute 事件的事件處理常式會判斷命令是否可以在目前命令目標上執行。The event handlers attached to the PreviewCanExecute and CanExecute events determine if the command can execute on the current command target.

下列範例將示範如何在應用程式的根目錄 CommandBinding 上建立 WindowThe following example shows how to create a CommandBinding on the root Window of an application. CommandBinding 會將 Open 命令與 ExecutedCanExecute 處理常式建立關聯。The CommandBinding associates the Open command with Executed and CanExecute handlers.

<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);
' Creating CommandBinding and attaching an Executed and CanExecute handler
Dim OpenCmdBinding As New CommandBinding(ApplicationCommands.Open, AddressOf OpenCmdExecuted, AddressOf OpenCmdCanExecute)

Me.CommandBindings.Add(OpenCmdBinding)

接下來,會建立 ExecutedRoutedEventHandlerCanExecuteRoutedEventHandlerNext, the ExecutedRoutedEventHandler and a CanExecuteRoutedEventHandler are created. ExecutedRoutedEventHandler 會開啟 MessageBox,會顯示一個字串,指出該命令已執行。The ExecutedRoutedEventHandler opens a MessageBox that displays a string saying the command has been executed. CanExecuteRoutedEventHandler 會將 CanExecute 屬性設定為 trueThe CanExecuteRoutedEventHandler sets the CanExecute property to true.

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);
}
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
void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
}
Private Sub OpenCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
    e.CanExecute = True
End Sub

CommandBinding 會附加至特定的物件,例如應用程式或控制項的根目錄 WindowA CommandBinding is attached to a specific object, such as the root Window of the application or a control. CommandBinding 所附加至的物件會定義繫結範圍。The object that the CommandBinding is attached to defines the scope of the binding. 例如,附加至命令目標上階的 CommandBinding 可以透過 Executed 事件到達,但無法到達附加至命令目標子系的 CommandBindingFor example, a CommandBinding attached to an ancestor of the command target can be reached by the Executed event, but a CommandBinding attached to a descendant of the command target cannot be reached. 這是 RoutedEvent 在引發事件之物件中浮動的直接結果。This is a direct consequence of the way a RoutedEvent tunnels and bubbles from the object that raises the event.

在某些情況下,CommandBinding 會附加至命令目標本身,例如 TextBox 類別與 CutCopyPaste 命令。In some situations the CommandBinding is attached to the command target itself, such as with the TextBox class and the Cut, Copy, and Paste commands. 但通常將 CommandBinding 附加至命令目標的上階會更方便,例如主要的 Window 或應用程式物件,特別是當相同的 CommandBinding 可用於多個命令目標時。Quite often though, it is more convenient to attach the CommandBinding to an ancestor of the command target, such as the main Window or the Application object, especially if the same CommandBinding can be used for multiple command targets. 這些都是當您要建立命令基礎結構時會想要考慮的設計決策。These are design decisions you will want to consider when you are creating your commanding infrastructure.

命令目標Command Target

命令目標是於其上執行命令的項目。The command target is the element on which the command is executed. 關於 RoutedCommand,命令目標是 ExecutedCanExecute 之路由啟動的項目。With regards to a RoutedCommand, the command target is the element at which routing of the Executed and CanExecute starts. 如前所述,在 WPFWPF 中,CommandTarget 上的 ICommandSource 屬性僅適用於當 ICommandRoutedCommand 時。As noted previously, in WPFWPF the CommandTarget property on ICommandSource is only applicable when the ICommand is a RoutedCommand. 如果 CommandTarget 是設定於 ICommandSource 上,並且對應的命令不是 RoutedCommand,則會忽略命令目標。If the CommandTarget is set on an ICommandSource and the corresponding command is not a RoutedCommand, the command target is ignored.

命令來源可以明確設定命令目標。The command source can explicitly set the command target. 如未定義命令目標,則具有鍵盤焦點的項目會作為命令目標。If the command target is not defined, the element with keyboard focus will be used as the command target. 將具有鍵盤焦點的項目作為命令目標的優點之一是,它讓應用程式開發人員使用相同的命令來源對多個目標叫用命令,但不必追蹤命令目標。One of the benefits of using the element with keyboard focus as the command target is that it allows the application developer to use the same command source to invoke a command on multiple targets without having to keep track of the command target. 例如,如果 MenuItem 在具有 控制項和 控制項的應用程式中叫用TextBox貼上PasswordBox命令,則目標可以是 TextBoxPasswordBox,取決於哪個控制項具有鍵盤焦點。For example, if a MenuItem invokes the Paste command in an application that has a TextBox control and a PasswordBox control, the target can be either the TextBox or PasswordBox depending on which control has keyboard focus.

下例示範如何在標記和程式碼後置中明確設定命令目標。The following example shows how to explicitly set the command target in markup and in code behind.

<StackPanel>
  <Menu>
    <MenuItem Command="ApplicationCommands.Paste"
              CommandTarget="{Binding ElementName=mainTextBox}" />
  </Menu>
  <TextBox Name="mainTextBox"/>
</StackPanel>
  // Creating the UI objects
  StackPanel mainStackPanel = new StackPanel();
  TextBox pasteTextBox = new TextBox();
  Menu stackPanelMenu = new Menu();
  MenuItem pasteMenuItem = new MenuItem();
 
  // Adding objects to the panel and the menu
  stackPanelMenu.Items.Add(pasteMenuItem);
  mainStackPanel.Children.Add(stackPanelMenu);
  mainStackPanel.Children.Add(pasteTextBox);

  // Setting the command to the Paste command
  pasteMenuItem.Command = ApplicationCommands.Paste;

  // Setting the command target to the TextBox
  pasteMenuItem.CommandTarget = pasteTextBox;
' Creating the UI objects
Dim mainStackPanel As New StackPanel()
Dim pasteTextBox As New TextBox()
Dim stackPanelMenu As New Menu()
Dim pasteMenuItem As New MenuItem()

' Adding objects to the panel and the menu
stackPanelMenu.Items.Add(pasteMenuItem)
mainStackPanel.Children.Add(stackPanelMenu)
mainStackPanel.Children.Add(pasteTextBox)

' Setting the command to the Paste command
pasteMenuItem.Command = ApplicationCommands.Paste

The CommandManagerThe CommandManager

CommandManager 提供許多與命令相關的功能。The CommandManager serves a number of command related functions. 會提供一組靜態方法,用於向特定項目新增和移除 PreviewExecutedExecutedPreviewCanExecuteCanExecute 事件處理常式。It provides a set of static methods for adding and removing PreviewExecuted, Executed, PreviewCanExecute, and CanExecute event handlers to and from a specific element. 會提供將 CommandBindingInputBinding 物件註冊到特定類別的方法。It provides a means to register CommandBinding and InputBinding objects onto a specific class. CommandManager 也會透過 RequerySuggested 事件提供一種方法,用於在引發 CanExecuteChanged 事件時通知命令。The CommandManager also provides a means, through the RequerySuggested event, to notify a command when it should raise the CanExecuteChanged event.

InvalidateRequerySuggested 方法會強制 CommandManager 引發 RequerySuggested 事件。The InvalidateRequerySuggested method forces the CommandManager to raise the RequerySuggested event. 出現應該停用/啟用命令的條件,卻非 CommandManager 所知的條件時,這很有用。This is useful for conditions that should disable/enable a command but are not conditions that the CommandManager is aware of.

命令程式庫Command Library

WPFWPF 提供一組預先定義的命令。provides a set of predefined commands. 命令程式庫包含下列類別:ApplicationCommandsNavigationCommandsMediaCommandsEditingCommandsComponentCommandsThe command library consists of the following classes: ApplicationCommands, NavigationCommands, MediaCommands, EditingCommands, and the ComponentCommands. 這些類別提供的命令,例如 CutBrowseBack 以及 BrowseForwardPlayStopPauseThese classes provide commands such as Cut, BrowseBack and BrowseForward, Play, Stop, and Pause.

這些命令許多都包含一組預設的輸入繫結。Many of these commands include a set of default input bindings. 例如,如果您指定應用程式處理複製命令,則會自動取得鍵盤系結 "CTRL + C",您也會取得其他輸入裝置的系結,例如 Tablet PC 畫筆手勢和語音資訊。For example, if you specify that your application handles the copy command, you automatically get the keyboard binding "CTRL+C" You also get bindings for other input devices, such as Tablet PC pen gestures and speech information.

當您參考使用 XAMLXAML 的各種命令程式庫中的命令時,通常會省略公開靜態命令屬性的文件庫類別的類別名稱。When you reference commands in the various command libraries using XAMLXAML, you can usually omit the class name of the library class that exposes the static command property. 命令名稱通常像字串一樣明確,且擁有提供命令邏輯群組的類型,但不一定用於去除混淆。Generally, the command names are unambiguous as strings, and the owning types exist to provide a logical grouping of commands but are not necessary for disambiguation. 例如,您可以指定 Command="Cut" 而不是更詳細的 Command="ApplicationCommands.Cut"For instance, you can specify Command="Cut" rather than the more verbose Command="ApplicationCommands.Cut". 這是內建在命令 WPFWPFXAMLXAML 處理器的方便機制 (更精確地說,這是 ICommand WPFWPF 處理器在載入階段參考的 XAMLXAML 類型轉換器行為)。This is a convenience mechanism that is built in to the WPFWPF XAMLXAML processor for commands (more precisely, it is a type converter behavior of ICommand, which the WPFWPF XAMLXAML processor references at load time).

建立自訂命令Creating Custom Commands

如果命令程式庫類別中的命令不符合您的需求,您可以建立自己的命令。If the commands in the command library classes do not meet your needs, then you can create your own commands. 有兩種方式可以建立自訂的命令。There are two ways to create a custom command. 第一種是從頭開始實作 ICommand 介面。The first is to start from the ground up and implement the ICommand interface. 另一種為更常見的方式,即建立 RoutedCommandRoutedUICommandThe other way, and the more common approach, is to create a RoutedCommand or a RoutedUICommand.

如需建立自訂 RoutedCommand 的範例,請參閱建立自訂的 RoutedCommand 範例For an example of creating a custom RoutedCommand, see Create a Custom RoutedCommand Sample.

另請參閱See also