首页 / 软件开发 / .NET编程技术 / WPF学习笔记 - 6. RoutedEvent
WPF学习笔记 - 6. RoutedEvent2010-10-11 rainsts.net yuhenWPF采取了路由事件机制,这样事件可以在可视树上层级传递。要知道 XAML 中控件都是由很多其他元素组合而成,比如我们单击了 Button 内部的 TextBlock 元素,Button 依然可以可以接收到该事件并触发 Button.Click。通常情况下,我们只是关心逻辑树上的事件过程。我们看看 Button Click 事件的实现。public abstract class ButtonBase : ContentControl, ICommandSource
{
public static readonly RoutedEvent ClickEvent;
static ButtonBase()
{
ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(ButtonBase));
......
}
public event RoutedEventHandler Click
{
add { base.AddHandler(ClickEvent, value); }
remove { base.RemoveHandler(ClickEvent, value); }
}
}
看上去很简单,不是吗?和依赖属性有点类似。注册路由事件时,我们可以选择不同的路由策略。管道传递(Tunneling): 事件首先在根元素上触发,然后向下层级传递,直到那个最初触发事件的子元素。冒泡(Bubbling): 事件从最初触发事件的子元素向根元素层级往上传递。直接(Direct): 事件仅在最初触发事件的子元素上触发。Window1.xaml<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
<Border MouseRightButtonDown="MouseRightButtonDown">
<StackPanel MouseRightButtonDown="MouseRightButtonDown">
<Button MouseRightButtonDown="MouseRightButtonDown">Test</Button>
</StackPanel>
</Border>
</Grid>
</Window>
Window1.xaml.cspublic partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show((sender as Label).Name);
}
}
在按钮上单击右键后,你会依次看到显示 "Button"、"StackPanel"、"Border" 的三个对话框,显然事件按照冒泡向根元素传递。有一点需要注意,WPF 路由事件参数有个 Handled 属性标记,一旦被某个程序标记为已处理,事件传递就会终止。测试一下。public partial class Window1 : Window
{
private void MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show(sender.GetType().Name);
if (sender.GetType().Name == "StackPanel") e.Handled = true;
}
}
很有效,Border.MouseRightButtonDown 不在有效。严格来说,事件并没有被终止,它依然会继续传递个上级或下级的元素,只是 WPF 没有触发事件代码而已。我们可以使用 AddHandler 方法重新注册一个新的事件处理方法,使得可以继续处理被终止的事件(注意: 如果事件没有终止,这会导致两次事件处理)。public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.border1.AddHandler(Border.MouseRightButtonDownEvent,
new MouseButtonEventHandler(MouseRightButtonDown), true);
}
private void MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show(sender.GetType().Name);
if (sender.GetType().Name == "StackPanel") e.Handled = true;
}
}
再运行试试,你会发现 Border.MouseRightButtonDown 被触发了。public void AddHandler(
RoutedEvent routedEvent,
Delegate handler,
bool handledEventsToo
)