如何:启用命令

更新:2007 年 11 月

下面的示例演示如何在 Windows Presentation Foundation (WPF) 中使用命令设置功能。 该示例演示如何将 RoutedCommandButton 关联,如何创建 CommandBinding,以及如何创建实现 RoutedCommand 的事件处理程序。 有关设置命令的更多信息,请参见命令概述

示例

代码的第一部分创建由 ButtonStackPanel 组成的用户界面 (UI),并创建一个将命令处理程序与 RoutedCommand 关联的 CommandBinding

ButtonCommand 属性与 Close 命令关联。

CommandBinding 添加到根 WindowCommandBindingCollection 中。ExecutedCanExecute 事件处理程序附加到此绑定并与 Close 命令关联。

没有 CommandBinding 就没有命令逻辑,而只是存在调用命令的机制。 在单击 Button 时,会针对命令目标引发 PreviewExecuted RoutedEvent,之后将引发 Executed RoutedEvent。 这些事件会遍历元素树,以查找该特定命令的 CommandBinding。 值得注意的是,由于 RoutedEvent 会在元素树中执行隧道和冒泡操作,因此一定要注意 CommandBinding 的放置位置。 如果 CommandBinding 位于命令目标的同级,或者它所在的节点不在 RoutedEvent 的路由上,将不会访问 CommandBinding

<Window x:Class="WCSamples.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="CloseCommand"
    Name="RootWindow"
    >
  <Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close"
                    Executed="CloseCommandHandler"
                    CanExecute="CanExecuteHandler"
                    />
  </Window.CommandBindings>
  <StackPanel Name="MainStackPanel">
    <Button Command="ApplicationCommands.Close" 
            Content="Close File" />
  </StackPanel>
</Window>
// Create ui elements.
StackPanel CloseCmdStackPanel = new StackPanel();
Button CloseCmdButton = new Button();
CloseCmdStackPanel.Children.Add(CloseCmdButton);

// Set Button's properties.
CloseCmdButton.Content = "Close File";
CloseCmdButton.Command = ApplicationCommands.Close;

// Create the CommandBinding.
CommandBinding CloseCommandBinding = new CommandBinding(
    ApplicationCommands.Close, CloseCommandHandler, CanExecuteHandler);

// Add the CommandBinding to the root Window.
RootWindow.CommandBindings.Add(CloseCommandBinding);

代码的第二部分实现 ExecutedCanExecute 事件处理程序。

Executed 处理程序调用一个方法来关闭已打开的文件。 CanExecute 处理程序调用一个方法来确定文件是否处于打开状态。 如果文件处于打开状态,CanExecute 将设置为 true;否则将设置为 false。

// Executed event handler.
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    // Calls a method to close the file and release resources.
    CloseFile();
}

// CanExecute event handler.
private void CanExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
{
    // Call a method to determine if there is a file open.
    // If there is a file open, then set CanExecute to true.
    if (IsFileOpened())
    {
        e.CanExecute = true;
    }
    // if there is not a file open, then set CanExecute to false.
    else
    {
        e.CanExecute = false;
    }
}

请参见

概念

命令概述