Como adicionar um manipulador de eventos usando código (WPF .NET)

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

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

Importante

A documentação do Guia da Área de Trabalho para .NET 7 e .NET 6 está em construção.

Pré-requisitos

O artigo pressupõe um conhecimento básico de eventos roteados e que você leu Visão geral de eventos roteados. Para seguir os exemplos neste artigo, é útil se você estiver familiarizado com XAML (Extensible Application Markup Language) e souber como escrever aplicativos Windows Presentation Foundation (WPF).

Sintaxe para atribuição de manipulador de eventos

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

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

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

Exemplo

O exemplo a seguir usa XAML para definir um Button nomeado ButtonCreatedByXaml e atribuir o método como seu Click manipulador de ButtonCreatedByXaml_Click eventos. Click é um evento roteado interno para botões derivados do 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 ButtonCreatedByXaml_Click manipuladores e atribuir o ButtonCreatedByCode_Click manipulador aos ButtonCreatedByCode elementos e ButtonCreatedByCode_ClickStackPanel1 . Os métodos de 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 nomeado ButtonCreatedByCode à árvore de elementos XAML já construída.
  2. Especifica propriedades para o novo botão, como nome, conteúdo e cor do plano de fundo.
  3. Atribui o ButtonCreatedByCode_Click manipulador de eventos a ButtonCreatedByCode.
  4. Atribui o mesmo ButtonCreatedByCode_Click manipulador de eventos ao StackPanel1.

Quando ButtonCreatedByCode é clicado:

  1. O Click evento roteado é gerado em ButtonCreatedByCode.
  2. O ButtonCreatedByCode_Click manipulador de eventos atribuído a ButtonCreatedByCode é acionado.
  3. O Click evento roteado percorre a árvore de elementos até StackPanel1.
  4. O ButtonCreatedByCode_Click manipulador de eventos atribuído a StackPanel1 é acionado.
  5. O Click evento roteado continua até a árvore de elementos potencialmente acionando outros manipuladores de eventos atribuídos a outros Click elementos atravessados.

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

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

Observação

Uma diferença fundamental 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 se conectar ao objeto de origem que gerou o evento. Como resultado, um evento sender roteado pode ser qualquer elemento atravessado na árvore de elementos.

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

Confira também