Практическое руководство. Включение команды

В следующем примере показано, как использовать команды в Windows Presentation Foundation (WPF). В этом примере показано, как связать объект RoutedCommand сButton, создать объект CommandBinding и обработчики событий, реализующие RoutedCommand. Дополнительные сведения о системе команд см. в разделе Общие сведения о системе команд.

Пример

Первый раздел кода создает пользовательский интерфейс, который состоит из Button и StackPanel, создает CommandBinding, который связывает обработчики команд с RoutedCommand.

Свойство CommandButton связано с командой Close.

CommandBinding добавляется в CommandBindingCollection корневого каталога Window. Обработчики событий Executed и CanExecute присоединены к этой привязке и связаны с командой Close.

Без CommandBinding нет логики команды, а есть только механизм для вызова команды. При выборе Button вызывается PreviewExecutedRoutedEvent в целевом объекте команды, за которым следует ExecutedRoutedEvent. Эти события проходят по дереву элементов, который выполняет поиск CommandBinding для этой конкретной команды. Стоит отметить, что поскольку RoutedEvent проводится как туннель и пузырек через дерево элементов, необходимо соблюдать осторожность при выборе точки размещения CommandBinding. Если объект CommandBinding находится в одноуровневом элементе целевого объекта команды или на другом узле, который не находится на маршруте RoutedEvent, доступ к CommandBinding не осуществляется.

<Window x:Class="WCSamples.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://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);
' Create ui elements.
Dim CloseCmdStackPanel As New StackPanel()
Dim CloseCmdButton As New Button()
CloseCmdStackPanel.Children.Add(CloseCmdButton)

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

' Create the CommandBinding.
Dim CloseCommandBinding As New CommandBinding(ApplicationCommands.Close, AddressOf CloseCommandHandler, AddressOf CanExecuteHandler)

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

В следующем разделе кода реализованы обработчики событий Executed и CanExecute.

Обработчик 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;
    }
}
' Executed event handler.
Private Sub CloseCommandHandler(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
    ' Calls a method to close the file and release resources.
    CloseFile()
End Sub

' CanExecute event handler.
Private Sub CanExecuteHandler(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
    ' Call a method to determine if there is a file open.
    ' If there is a file open, then set CanExecute to true.
    If IsFileOpened() Then
        e.CanExecute = True
    ' if there is not a file open, then set CanExecute to false.
    Else
        e.CanExecute = False
    End If
End Sub

См. также