Cómo: Habilitar un comando

En el ejemplo siguiente se muestra cómo usar comandos en Windows Presentation Foundation (WPF). El ejemplo muestra cómo asociar un RoutedCommand a un Button, crear un CommandBinding, y crear los controladores de eventos que implementan el RoutedCommand. Para obtener más información sobre los comandos, consulte Información general sobre comandos.

Ejemplo

La primera sección de código crea la interfaz de usuario (UI), que consiste en un Button y un StackPanel, y crea un CommandBinding que asocia los controladores de comandos con el RoutedCommand.

La propiedad Command del Button está asociada al comando Close.

El CommandBinding se añade al CommandBindingCollection de la raíz Window. Los controladores de eventos Executed y CanExecute se adjuntan a este enlace y se asocian al comando Close.

Sin el CommandBinding no hay lógica de comando, solo un mecanismo para invocar el comando. Cuando se pulsa el Button, se inicia el PreviewExecutedRoutedEvent en el objetivo del comando seguido del ExecutedRoutedEvent. Estos eventos atraviesan el árbol de elementos buscando un CommandBinding para este comando determinado. Vale la pena señalar que debido a que los RoutedEvent hacen un túnel y burbujean a través del árbol de elementos, se debe tener cuidado en el lugar donde se coloca el CommandBinding. Si el CommandBinding está en un elemento relacionado del destino de comando o en otro nodo que no esté en la ruta del RoutedEvent, no se accederá al 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)

La siguiente sección de código implementa los controladores de eventos Executed y CanExecute.

El controlador Executed llama a un método para cerrar el archivo abierto. El controlador CanExecute llama a un método para determinar si un archivo está abierto. Si un archivo está abierto, CanExecute se establece en true; en caso contrario, se establece en 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

Vea también