Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
È possibile assegnare un gestore eventi a un elemento in Windows Presentation Foundation (WPF) usando markup o code-behind. Anche se è consuetudine assegnare un gestore eventi in XAML (Extensible Application Markup Language), a volte potrebbe essere necessario assegnare un gestore eventi nel code-behind. Ad esempio, usare il codice quando:
- Assegni un gestore eventi a un elemento dopo il caricamento della pagina di markup che contiene l'elemento.
- Aggiungere un elemento e assegnare il relativo gestore eventi dopo la pagina di markup che conterrà il caricamento dell'elemento.
- Si definisce l'albero degli elementi per l'applicazione interamente nel codice.
Prerequisiti
L'articolo presuppone una conoscenza di base degli eventi indirizzati e che tu abbia letto la panoramica degli eventi indirizzati. Per seguire gli esempi in questo articolo, è utile se si ha familiarità con Extensible Application Markup Language (XAML) e si sa come scrivere applicazioni Windows Presentation Foundation (WPF).
Sintassi per l'assegnazione del gestore eventi
C# supporta l'assegnazione del gestore eventi usando:
-
+=Operatore , che viene usato anche nel modello di gestione degli eventi CLR (Common Language Runtime). - Metodo UIElement.AddHandler.
VB supporta l'assegnazione del gestore eventi tramite:
- Istruzione AddHandler con l'operatore AddressOf , che viene usata anche nel modello di gestione degli eventi CLR.
- Parola chiave Handle nella definizione del gestore eventi. Per altre informazioni, vedere Gestione degli eventi di Visual Basic e WPF.
- Metodo UIElement.AddHandler , insieme all'operatore
AddressOfper fare riferimento al gestore eventi.
Esempio
L'esempio seguente usa XAML per definire un Button oggetto denominato ButtonCreatedByXaml e per assegnare il ButtonCreatedByXaml_Click metodo come Click gestore eventi.
Click è un evento predefinito indirizzato per i pulsanti che derivano da ButtonBase.
<StackPanel Name="StackPanel1">
<Button
Name="ButtonCreatedByXaml"
Click="ButtonCreatedByXaml_Click"
Content="Create a new button with an event handler"
Background="LightGray">
</Button>
</StackPanel>
Nell'esempio viene utilizzato il code-behind per implementare i gestori ButtonCreatedByXaml_Click e ButtonCreatedByCode_Click, e per assegnare il gestore ButtonCreatedByCode_Click agli elementi ButtonCreatedByCode e StackPanel1. I metodi del gestore eventi possono essere implementati solo nel 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 si fa clic e il relativo gestore eventi viene eseguito a ButtonCreatedByXaml_Click livello di codice:
- Aggiunge un nuovo pulsante denominato
ButtonCreatedByCodeall'albero degli elementi XAML già costruito. - Specifica le proprietà per il nuovo pulsante, ad esempio il nome, il contenuto e il colore di sfondo.
- Assegna il
ButtonCreatedByCode_Clickgestore eventi aButtonCreatedByCode. - Assegna lo stesso
ButtonCreatedByCode_Clickgestore eventi aStackPanel1.
Quando si fa clic su ButtonCreatedByCode:
- L'evento indirizzato Click viene generato in
ButtonCreatedByCode. - Viene attivato il
ButtonCreatedByCode_Clickgestore eventi assegnato aButtonCreatedByCode. - L'evento indirizzato
Clickattraversa l'albero degli elementi fino aStackPanel1. - Viene attivato il
ButtonCreatedByCode_Clickgestore eventi assegnato aStackPanel1. - L'evento
Clickindirizzato continua l'albero degli elementi attivando potenzialmente altriClickgestori eventi assegnati ad altri elementi attraversati.
Il gestore eventi ButtonCreatedByCode_Click ottiene le informazioni seguenti sull'evento che lo ha attivato:
- Oggetto sender , ovvero l'elemento a cui è assegnato il gestore eventi. Il valore di
sendersaràButtonCreatedByCodela prima volta che il gestore viene eseguito, eStackPanel1la seconda volta. - Oggetto RoutedEventArgs.Source, ovvero l'elemento che ha originariamente generato l'evento. In questo esempio il
Sourceè sempreButtonCreatedByCode.
Annotazioni
Una differenza fondamentale tra un evento indirizzato e un evento CLR consiste nel fatto che un evento indirizzato attraversa l'albero degli elementi, cercando gestori, mentre un evento CLR non attraversa l'albero degli elementi e i gestori possono essere collegati solo all'oggetto di origine che ha generato l'evento. Di conseguenza, un evento indirizzato sender può essere qualsiasi elemento attraversato nell'albero degli elementi.
Per altre informazioni su come creare e gestire eventi indirizzati, vedere Come creare un evento indirizzato personalizzato e Gestire un evento indirizzato
Vedere anche
.NET Desktop feedback