Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
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:
- A instrução AddHandler, com o operador AddressOf, é também usada no modelo de manipulação de eventos do CLR.
- A palavra-chave Handles na definição do manipulador de eventos. Para obter mais informações, consulte Manipulação de eventos do Visual Basic e do WPF.
- O método UIElement.AddHandler, juntamente com o operador
AddressOfpara fazer referência ao manipulador de eventos.
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:
- Adiciona um novo botão chamado
ButtonCreatedByCodeà árvore de elementos XAML já construída. - Especifica as propriedades do novo botão, como o nome, o conteúdo e a cor da tela de fundo.
- Atribui o manipulador de eventos
ButtonCreatedByCode_ClickaButtonCreatedByCode. - Atribui o mesmo manipulador de eventos
ButtonCreatedByCode_ClickaStackPanel1.
Quando ButtonCreatedByCode é clicado:
- O evento roteado Click é gerado em
ButtonCreatedByCode. - O manipulador de eventos
ButtonCreatedByCode_Clickatribuído aButtonCreatedByCodeé executado. - O evento roteado
Clickpercorre a árvore de elementos atéStackPanel1. - O manipulador de eventos
ButtonCreatedByCode_Clickatribuído aStackPanel1é executado. - O evento roteado
Clickcontinua subindo pela árvore de elementos, podendo acionar outros manipuladores de eventosClickatribuí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
senderseráButtonCreatedByCodeda primeira vez que o manipulador for executado eStackPanel1da segunda vez. - O objeto RoutedEventArgs.Source, que é o elemento que originalmente gerou o evento. Neste exemplo, o
Sourceé sempreButtonCreatedByCode.
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
.NET Desktop feedback