Compartir a través de


Cómo: Crear un comando RoutedCommand

En este ejemplo se muestra cómo crear un comando RoutedCommand personalizado y cómo implementarlo creando un controlador ExecutedRoutedEventHandler y un controlador CanExecuteRoutedEventHandler y asociándolos a un enlace CommandBinding. Para obtener más información sobre los comandos, vea Información general sobre comandos.

Ejemplo

El primer paso para crear RoutedCommand es definir el comando y crear una instancia de él.

        Public Shared CustomRoutedCommand As New RoutedCommand()
public static RoutedCommand CustomRoutedCommand = new RoutedCommand();

Para utilizar el comando en una aplicación, es preciso crear los controladores de eventos que definen qué hace el comando

        Private Sub ExecutedCustomCommand(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
            MessageBox.Show("Custom Command Executed")
        End Sub
private void ExecutedCustomCommand(object sender,
    ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Custom Command Executed");
}
        ' CanExecuteRoutedEventHandler that only returns true if
        ' the source is a control.
        Private Sub CanExecuteCustomCommand(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
            Dim target As Control = TryCast(e.Source, Control)

            If target IsNot Nothing Then
                e.CanExecute = True
            Else
                e.CanExecute = False
            End If
        End Sub
// CanExecuteRoutedEventHandler that only returns true if
// the source is a control.
private void CanExecuteCustomCommand(object sender, 
    CanExecuteRoutedEventArgs e)
{
    Control target = e.Source as Control;

    if(target != null)
    {
        e.CanExecute = true;
    }
    else
    {
        e.CanExecute = false;
    }
}

Luego, se crea un enlace CommandBinding que asocia el comando a los controladores de eventos. CommandBinding se crea para un objeto concreto. Este objeto define el ámbito de CommandBinding en el árbol de elementos

<Window x:Class="SDKSamples.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:SDKSamples"
    Height="600" Width="800"
    >
  <Window.CommandBindings>
    <CommandBinding Command="{x:Static custom:Window1.CustomRoutedCommand}"
                    Executed="ExecutedCustomCommand"
                    CanExecute="CanExecuteCustomCommand" />
  </Window.CommandBindings>
            Dim customCommandBinding As New CommandBinding(CustomRoutedCommand, AddressOf ExecutedCustomCommand, AddressOf CanExecuteCustomCommand)

            ' attach CommandBinding to root window
            Me.CommandBindings.Add(customCommandBinding)
CommandBinding customCommandBinding = new CommandBinding(
    CustomRoutedCommand, ExecutedCustomCommand, CanExecuteCustomCommand);

// attach CommandBinding to root window
this.CommandBindings.Add(customCommandBinding);

El paso final consiste en invocar el comando. Una manera de invocar un comando es asociarlo a una interfaz ICommandSource, como un Button.

<StackPanel>
  <Button Command="{x:Static custom:Window1.CustomRoutedCommand}"
          Content="CustomRoutedCommand"/>
</StackPanel>
            ' create the ui
            Dim CustomCommandStackPanel As New StackPanel()
            Dim CustomCommandButton As New Button()
            CustomCommandStackPanel.Children.Add(CustomCommandButton)

            CustomCommandButton.Command = CustomRoutedCommand
// create the ui
StackPanel CustomCommandStackPanel = new StackPanel();
Button CustomCommandButton = new Button();
CustomCommandStackPanel.Children.Add(CustomCommandButton);

CustomCommandButton.Command = CustomRoutedCommand;

Cuando se hace clic en el objeto Button, se llama al método Execute del comando RoutedCommand personalizado. RoutedCommand provoca los eventos enrutados PreviewExecuted y Executed. Estos eventos recorren el árbol de elementos en busca de un enlace CommandBinding para ese comando concreto. Si se encuentra un enlace CommandBinding, se llama al controlador ExecutedRoutedEventHandler asociado a CommandBinding.

Vea también

Referencia

RoutedCommand

Conceptos

Información general sobre comandos