如何:处理路由事件
此示例演示浮升事件的工作原理以及如何编写可处理路由事件数据的处理程序。
例
在 Windows Presentation Foundation (WPF)中,元素排列在元素树结构中。 父元素可以参与处理元素树中由子元素最初触发的事件。 这都是因为事件路由。
路由事件通常遵循以下两个路由策略之一:浮升和隧道。 此示例重点介绍冒泡事件,并使用 ButtonBase.Click 事件来显示路由的工作原理。
以下示例创建两个 Button 控件,并使用 XAML 属性语法将事件处理程序附加到一个共同的父元素,在此示例中是 StackPanel。 该示例使用属性语法将事件处理程序附加到 StackPanel 父元素,而不是为每个 Button 子元素附加单独的事件处理程序。 此事件处理模式展示了如何使用事件路由技术来减少附加处理程序的元素数。 每个 Button 的所有浮升事件都通过父元素路由。
请注意,在父 StackPanel 元素上,指定为特性的 Click 事件名称可通过命名 Button 类来进行部分限定。 Button 类是一个 ButtonBase 派生类,其成员列表中具有 Click 事件。 如果正在处理的事件不存在于附加路由事件处理程序的元素的成员列表中,则附加事件处理程序的此部分限定技术是必需的。
<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>
以下示例处理 Click 事件。 该示例报告哪个元素处理事件,以及哪个元素引发该事件。 当用户单击任一按钮时,将执行事件处理程序。
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