Partilhar via


Como criar um RoutedCommand

Este exemplo mostra como criar um RoutedCommand personalizado e como implementar o comando personalizado criando um ExecutedRoutedEventHandler e um CanExecuteRoutedEventHandler e anexando-os a um CommandBinding. Para obter mais informações sobre comandos, consulte o Commanding Overview.

Exemplo

O primeiro passo para criar um RoutedCommand é definir o comando e instanciá-lo.

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

Para usar o comando em um aplicativo, manipuladores de eventos que definem o que o comando faz devem ser criados

private void ExecutedCustomCommand(object sender,
    ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Custom Command Executed");
}
Private Sub ExecutedCustomCommand(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
    MessageBox.Show("Custom Command Executed")
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;
    }
}
' 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

Em seguida, é criado um CommandBinding que associa o comando aos manipuladores de eventos. O CommandBinding é criado em um objeto específico. Este objeto define o escopo do CommandBinding na árvore de elementos

<Window x:Class="SDKSamples.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://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);
Dim customCommandBinding As New CommandBinding(CustomRoutedCommand, AddressOf ExecutedCustomCommand, AddressOf CanExecuteCustomCommand)

' attach CommandBinding to root window
Me.CommandBindings.Add(customCommandBinding)

A etapa final é invocar o comando. Uma maneira de invocar um comando é associá-lo a um ICommandSource, como um 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;
' create the ui
Dim CustomCommandStackPanel As New StackPanel()
Dim CustomCommandButton As New Button()
CustomCommandStackPanel.Children.Add(CustomCommandButton)

CustomCommandButton.Command = CustomRoutedCommand

Quando o botão é clicado, o método Execute do componente personalizado RoutedCommand é chamado. O RoutedCommand aciona os eventos encaminhados PreviewExecuted e Executed. Esses eventos percorrem a árvore de elementos em busca de uma CommandBinding para este comando específico. Se um CommandBinding for encontrado, o ExecutedRoutedEventHandler associado a CommandBinding será chamado.

Ver também