Compartir a través de


Cómo: Crear un comando RoutedCommand

Actualización: noviembre 2007

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 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 void ExecutedCustomCommand(object sender,
    ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Custom Command Executed");
}
// 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>
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
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

Conceptos

Información general sobre comandos

Referencia

RoutedCommand