Como habilitar um comando

O exemplo a seguir demonstra como usar comandos no Windows Presentation Foundation (WPF). O exemplo mostra como associar a a RoutedCommand a um Button, criar um CommandBinding, e criar os manipuladores de eventos que implementam o RoutedCommand. Para obter mais informações sobre comandos, consulte Visão geral de comandos.

Exemplo

A primeira seção do código cria a interface do usuário, que consiste em a Button e um StackPanel, e cria um CommandBinding que associa os manipuladores de comando ao RoutedCommand.

A Command propriedade do Button está associada ao Close comando.

O CommandBinding é adicionado ao CommandBindingCollection da raiz Window. Os Executed manipuladores de eventos and CanExecute são anexados a essa associação e associados ao Close comando.

Sem o CommandBinding não há lógica de comando, apenas um mecanismo para invocar o comando. Quando o Button é clicado, o PreviewExecuted RoutedEvent é gerado no destino do comando seguido pelo Executed RoutedEvent. Esses eventos percorrem a árvore de elementos procurando um CommandBinding para esse comando específico. Vale a pena notar que, como RoutedEvent o túnel e a bolha atravessam a árvore de elementos, deve-se tomar cuidado onde o CommandBinding é colocado. Se o CommandBinding estiver em um irmão do destino de comando ou em outro nó que não esteja na rota do RoutedEvent, o não CommandBinding será acessado.

<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)

A próxima seção do código implementa os Executed manipuladores de eventos e CanExecute .

O Executed manipulador chama um método para fechar o arquivo aberto. O CanExecute manipulador chama um método para determinar se um arquivo está aberto. Se um arquivo estiver aberto, CanExecute será definido como true; caso contrário, será definido como 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

Confira também