Procedura: Gestire un evento indirizzato

Questo esempio illustra il funzionamento degli eventi di bubbling e spiega come scrivere un gestore in grado di elaborare i dati dell'evento indirizzato.

Esempio

In Windows Presentation Foundation (WPF) gli elementi vengono disposti in una struttura ad albero degli elementi. L'elemento padre può partecipare alla gestione di eventi inizialmente generati dagli elementi figlio nell'albero degli elementi. Questo è possibile grazie al routing di eventi.

Per gli eventi indirizzati si usa in genere una delle due strategie di routing seguenti: bubbling o tunneling. Questo esempio è incentrato sull'evento di bubbling e usa l'evento per mostrare il funzionamento del ButtonBase.Click routing.

L'esempio seguente crea due Button controlli e usa la sintassi degli attributi XAML per associare un gestore eventi a un elemento padre comune, che in questo esempio è StackPanel. Anziché associare singoli gestori eventi per ogni Button elemento figlio, nell'esempio viene usata la sintassi degli attributi per associare il gestore eventi all'elemento StackPanel padre. Questo criterio di gestione degli eventi illustra in che modo usare il routing di eventi come tecnica per ridurre il numero di elementi a cui è associato un gestore. Tutti gli eventi di bubbling per ogni Button route attraverso l'elemento padre.

Si noti che nell'elemento padre StackPanel il Click nome dell'evento specificato come attributo è parzialmente qualificato assegnando alla classe un Button nome. La Button classe è una ButtonBase classe derivata con l'evento nell'elenco Click dei membri. La tecnica della qualifica parziale per l'associazione di un gestore eventi è necessaria se l'evento che viene gestito non esiste nell'elenco dei membri dell'elemento a cui è associato il gestore dell'evento indirizzato.

<StackPanel
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.RoutedEventHandle"
  Name="dpanel"
  Button.Click="HandleClick"
>
  <StackPanel.Resources>
      <Style TargetType="{x:Type Button}">
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="250"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
      </Style>
  </StackPanel.Resources>
  <Button Name="Button1">Item 1</Button>
  <Button Name="Button2">Item 2</Button>
  <TextBlock Name="results"/>
</StackPanel>

Nell'esempio seguente viene gestito l'evento Click . L'esempio stabilisce quale elemento gestisce l'evento e quale elemento genera l'evento. Il gestore eventi viene eseguito quando l'utente fa clic su uno dei pulsanti.

public partial class RoutedEventHandle : StackPanel
{
    StringBuilder eventstr = new StringBuilder();
    void HandleClick(object sender, RoutedEventArgs args)
    {
        // Get the element that handled the event.
        FrameworkElement fe = (FrameworkElement)sender;
        eventstr.Append("Event handled by element named ");
        eventstr.Append(fe.Name);
        eventstr.Append("\n");

        // Get the element that raised the event.
        FrameworkElement fe2 = (FrameworkElement)args.Source;
        eventstr.Append("Event originated from source element of type ");
        eventstr.Append(args.Source.GetType().ToString());
        eventstr.Append(" with Name ");
        eventstr.Append(fe2.Name);
        eventstr.Append("\n");

        // Get the routing strategy.
        eventstr.Append("Event used routing strategy ");
        eventstr.Append(args.RoutedEvent.RoutingStrategy);
        eventstr.Append("\n");

        results.Text = eventstr.ToString();
    }
}
Private eventstr As New Text.StringBuilder()

Private Sub HandleClick(ByVal sender As Object, ByVal args As RoutedEventArgs)
    ' Get the element that handled the event.
    Dim fe As FrameworkElement = DirectCast(sender, FrameworkElement)
    eventstr.Append("Event handled by element named ")
    eventstr.Append(fe.Name)
    eventstr.Append(vbLf)

    ' Get the element that raised the event. 
    Dim fe2 As FrameworkElement = DirectCast(args.Source, FrameworkElement)
    eventstr.Append("Event originated from source element of type ")
    eventstr.Append(args.Source.[GetType]().ToString())
    eventstr.Append(" with Name ")
    eventstr.Append(fe2.Name)
    eventstr.Append(vbLf)

    ' Get the routing strategy.
    eventstr.Append("Event used routing strategy ")
    eventstr.Append(args.RoutedEvent.RoutingStrategy)
    eventstr.Append(vbLf)

    results.Text = eventstr.ToString()
End Sub

Vedi anche