3.3.1 路由事件的实现
- 路由事件的类型为 System.Windows.RoutedEvent
- 所有的路由事件成员都必须是 public、static,并且有一个 Event 作为后缀。
- 路由事件通常通过调用 EventManager.RegisterRoutedEvent 静态方法创建。这个方法需要三个参数:
- 路由事件的名称
- 作为枚举值的事件的路由策略
- 事件处理程序的类型
- 路由事件的所有者类类型
- 路由事件定义完成后,最好添加 .NET 事件包装器(数据接口)实现对路由事件的访问,这样可以在 XAML 中用事件特性语法添加一个事件处理程序。
- 在路由事件的事件包装器中,除了 AddHandler / RemoveHandler 调用外,不应该添加任何其它逻辑。
例如:
public class Button : ButtonBase
{
// 路由事件
public new static readonly RoutedEvent ClickEvent;
static Button()
{
// 注册时间
Button.ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Button));
}
// .NET事件包装器(可选)
public new event RoutedEventHandler Click
{
add
{
this.AddHandler(Button.ClickEvent, value);
}
remove
{
this.RemoveHandler(Button.ClickEvent, value);
}
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
// 触发事件
this.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
}
}
注意:
- AddHandler、RemoveHandler这两个方法都是继承自System.Windows.UIElement。通过调用这两个方法可以向一个适当的路由事件添加一个委托或者从路由事件移除一个委托。
- RaiseEvent也是继承自System.Windows.UIElement。它用来触发路由事件。
- public new static readonly RoutedEvent ClickEvent;public new event RoutedEventHandler Click 中关键字new的作用是有意隐藏ButtonBase中对ClickEvent和Click的定义。