Compartilhar via


Como criar um RoutedCommand

Este exemplo mostra como criar um comando personalizado e como implementar o comando RoutedCommand personalizado criando um e um e anexando-os a um ExecutedRoutedEventHandlerCanExecuteRoutedEventHandlerCommandBindingarquivo . Para obter mais informações sobre comandos, consulte Visão geral de comandos.

Exemplo

A primeira etapa na criação de 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, os 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 na árvore de CommandBinding 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 , como um ICommandSourceButtonarquivo .

<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 Execute método no personalizado RoutedCommand é chamado. O RoutedCommand levanta os PreviewExecuted eventos e Executed encaminha. Esses eventos atravessam a árvore de elementos procurando um CommandBinding para esse comando específico. Se um CommandBinding for encontrado, o ExecutedRoutedEventHandler associado a CommandBinding é chamado.

Confira também