Compartilhar via


Como adicionar um manipulador de eventos usando código

Você pode atribuir um manipulador de eventos a um elemento no WPF (Windows Presentation Foundation) usando marcação ou code-behind. Embora seja costume atribuir um manipulador de eventos em XAML (Extensible Application Markup Language), às vezes você pode ter que atribuir um manipulador de eventos no code-behind. Por exemplo, use o código quando:

  • Você atribui um manipulador de eventos a um elemento após a página de marcação que contém o elemento carregado.
  • Você adiciona um elemento e atribui seu manipulador de eventos após a página de marcação que conterá o elemento ser carregada.
  • Você define a árvore de elementos para seu aplicativo inteiramente no código.

Pré-requisitos

O artigo pressupõe um conhecimento básico dos eventos roteados e que você leu Visão Geral de Eventos Roteados. Para seguir os exemplos neste artigo, ele ajuda se você estiver familiarizado com XAML (Extensible Application Markup Language) e saber como escrever aplicativos do WPF (Windows Presentation Foundation).

Sintaxe para atribuição do manipulador de eventos

O C# dá suporte à atribuição do manipulador de eventos usando:

  • O operador +=, que também é usado no modelo de tratamento de eventos CLR (Common Language Runtime).
  • O método UIElement.AddHandler.

O VB dá suporte à atribuição do manipulador de eventos usando:

Exemplo

O exemplo a seguir usa XAML para definir um Button chamado ButtonCreatedByXaml e atribuir o método ButtonCreatedByXaml_Click como seu manipulador de eventos Click. Click é um evento roteado integrado para botões que derivam de ButtonBase.

<StackPanel Name="StackPanel1">
    <Button
        Name="ButtonCreatedByXaml" 
        Click="ButtonCreatedByXaml_Click"
        Content="Create a new button with an event handler"
        Background="LightGray">
    </Button>
</StackPanel>

O exemplo usa code-behind para implementar os manipuladores de ButtonCreatedByXaml_Click e ButtonCreatedByCode_Click e atribuir o manipulador de ButtonCreatedByCode_Click aos elementos ButtonCreatedByCode e StackPanel1. Os métodos do manipulador de eventos só podem ser implementados em code-behind.

// The click event handler for the existing button 'ButtonCreatedByXaml'.
private void ButtonCreatedByXaml_Click(object sender, RoutedEventArgs e)
{
    // Create a new button.
    Button ButtonCreatedByCode = new();

    // Specify button properties.
    ButtonCreatedByCode.Name = "ButtonCreatedByCode";
    ButtonCreatedByCode.Content = "New button and event handler created in code";
    ButtonCreatedByCode.Background = Brushes.Yellow;

    // Add the new button to the StackPanel.
    StackPanel1.Children.Add(ButtonCreatedByCode);

    // Assign an event handler to the new button using the '+=' operator.
    ButtonCreatedByCode.Click += new RoutedEventHandler(ButtonCreatedByCode_Click);

    // Assign an event handler to the new button using the AddHandler method.
    // AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click);

    // Assign an event handler to the StackPanel using the AddHandler method.
    StackPanel1.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ButtonCreatedByCode_Click));
}

// The Click event handler for the new button 'ButtonCreatedByCode'.
private void ButtonCreatedByCode_Click(object sender, RoutedEventArgs e)
{
    string sourceName = ((FrameworkElement)e.Source).Name;
    string senderName = ((FrameworkElement)sender).Name;

    Debug.WriteLine($"Routed event handler attached to {senderName}, " +
        $"triggered by the Click routed event raised by {sourceName}.");
}
' The click event handler for the existing button 'ButtonCreatedByXaml'.
Private Sub ButtonCreatedByXaml_Click(sender As Object, e As RoutedEventArgs)

    ' Create a new button and specify button properties.
    Dim ButtonCreatedByCode As New Button With {
        .Name = "ButtonCreatedByCode",
        .Content = "New button and event handler created in code",
        .Background = Brushes.Yellow
    }

    ' Add the new button to the StackPanel.
    StackPanel1.Children.Add(ButtonCreatedByCode)

    ' Assign an event handler to the new button using the AddHandler statement.
    AddHandler ButtonCreatedByCode.Click, AddressOf ButtonCreatedByCode_Click

    ' Assign an event handler to the new button using the AddHandler method.
    ' ButtonCreatedByCode.AddHandler(ButtonBase.ClickEvent, New RoutedEventHandler(AddressOf ButtonCreatedByCode_Click))

    ' Assign an event handler to the StackPanel using the AddHandler method.
    StackPanel1.AddHandler(ButtonBase.ClickEvent, New RoutedEventHandler(AddressOf ButtonCreatedByCode_Click))

End Sub

' The Click event handler for the new button 'ButtonCreatedByCode'.
Private Sub ButtonCreatedByCode_Click(sender As Object, e As RoutedEventArgs)

    Dim sourceName As String = CType(e.Source, FrameworkElement).Name
    Dim senderName As String = CType(sender, FrameworkElement).Name

    Debug.WriteLine($"Routed event handler attached to {senderName}, " +
        $"triggered by the Click routed event raised by {sourceName}.")

End Sub

Quando ButtonCreatedByXaml é clicado e seu manipulador de eventos é executado, ButtonCreatedByXaml_Click programaticamente:

  1. Adiciona um novo botão chamado ButtonCreatedByCode à árvore de elementos XAML já construída.
  2. Especifica as propriedades do novo botão, como o nome, o conteúdo e a cor da tela de fundo.
  3. Atribui o manipulador de eventos ButtonCreatedByCode_Click a ButtonCreatedByCode.
  4. Atribui o mesmo manipulador de eventos ButtonCreatedByCode_Click a StackPanel1.

Quando ButtonCreatedByCode é clicado:

  1. O evento roteado Click é gerado em ButtonCreatedByCode.
  2. O manipulador de eventos ButtonCreatedByCode_Click atribuído a ButtonCreatedByCode é executado.
  3. O evento roteado Click percorre a árvore de elementos até StackPanel1.
  4. O manipulador de eventos ButtonCreatedByCode_Click atribuído a StackPanel1 é executado.
  5. O evento roteado Click continua subindo pela árvore de elementos, podendo acionar outros manipuladores de eventos Click atribuídos a outros elementos percorridos.

O manipulador de eventos ButtonCreatedByCode_Click obtém as seguintes informações sobre o evento que o disparou:

  • O objeto sender, que é o elemento ao qual o manipulador de eventos é atribuído. O sender será ButtonCreatedByCode da primeira vez que o manipulador for executado e StackPanel1 da segunda vez.
  • O objeto RoutedEventArgs.Source, que é o elemento que originalmente gerou o evento. Neste exemplo, o Source é sempre ButtonCreatedByCode.

Observação

Uma diferença importante entre um evento roteado e um evento CLR é que um evento roteado atravessa a árvore de elementos, procurando manipuladores, enquanto um evento CLR não atravessa a árvore de elementos e os manipuladores só podem anexar ao objeto de origem que gerou o evento. Como resultado, um evento roteado sender pode ser qualquer elemento percorrido na árvore de elementos.

Para obter mais informações sobre como criar e manipular eventos roteado, consulte Como criar um evento roteado personalizado e manipular um evento roteado

Consulte também