命令概述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 调用文本类、图像类和 Web 浏览器中的“剪切”命令,但执行“剪切”操作的实际逻辑由执行剪切的应用程序定义。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,以便在单击时它将调用 TextBox 上的 Paste 命令,假定 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. ICommandWPFWPF 实现是 RoutedCommand 类,并且是本概述的重点。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. RoutedCommandExecuteCanExecute 方法不包含该命令的应用程序逻辑,而是引发通过元素树通行和浮升的路由事件,直到遇到具有 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.

RoutedCommand 上的 Execute 方法引发命令目标上的 PreviewExecutedExecuted 事件。The Execute method on a RoutedCommand raises the PreviewExecuted and the Executed events on the command target. RoutedCommand 上的 CanExecute 方法引发命令目标上的 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:

实现 ICommandSourceWPFWPF 类是 ButtonBaseMenuItemHyperlinkInputBindingThe WPFWPF classes that implement ICommandSource are ButtonBase, MenuItem, Hyperlink, and InputBinding. 单击 ButtonBaseMenuItemHyperlink 时,调用一个命令,当执行与其关联的 InputGesture 时,InputBinding 调用命令。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.

以下示例显示如何将 ContextMenu 中的 MenuItem 用作 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. 命令源可以使用 CanExecute 方法查询 RoutedCommand 的当前状态。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. KeyGesture 由一个 Key 和一组 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.

以下示例演示如何在 KeyGestureRoutedCommand 之间创建 KeyBindingThe 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)

InputGesture 关联到 RoutedCommand 的另一种方法是将 InputGesture 添加到 RoutedCommand 上的 InputGestureCollectionAnother way to associate an InputGesture to a RoutedCommand is to add the InputGesture to the InputGestureCollection on the RoutedCommand.

以下示例演示如何将 KeyGesture 添加到 RoutedCommandInputGestureCollection 中。The 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.

以下示例演示如何在应用程序的根 Window 上创建 CommandBindingThe following example shows how to create a CommandBinding on the root Window of an application. CommandBindingOpen 命令与 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. CanExecuteRoutedEventHandlerCanExecute 属性设置为 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 中,仅当 ICommandRoutedCommand 时,ICommandSource 上的 CommandTarget 属性才适用。As noted previously, in WPFWPF the CommandTarget property on ICommandSource is only applicable when the ICommand is a RoutedCommand. 如果在 ICommandSource 上设置 CommandTarget 并且相应的命令不是 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 控件的应用程序中调用“Paste”命令,则目标可以是 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

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. 这些类提供诸如 CutBrowseBackBrowseForwardPlayStopPause 的命令。These 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 PCTablet 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 PCTablet 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". 这是针对命令内置于 WPFWPF XAMLXAML 处理器中的便捷机制(更准确地说,它是 WPFWPF XAMLXAML 处理器在加载时所引用的 ICommand 的类型转换器行为)。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