步骤:
- 生声明并注册路由事件
- 为路由事件添加CLR事件包装
- 创建可以激发路由事件的方法
示例:创建一个报告事件发生时间的事件
首先,创建一个RoutedEventArgs的派生类
internal class TimeEventArgs:RoutedEventArgs
{
public TimeEventArgs(RoutedEvent routedEvent,object source) : base(routedEvent, source) { }
public DateTime ClickTime { get; set; }
}
然后,创建一个Button的派生类并添加路由事件
internal class TimeButton:Button
{
//声明注册
public static readonly RoutedEvent ReportTimeEvent = EventManager.RegisterRoutedEvent(
"ReportTime", RoutingStrategy.Bubble, typeof(EventHandler<TimeEventArgs>), typeof(TimeButton));
//CLR事件包装
public event RoutedEventHandler ReportTime
{
add { this.AddHandler(ReportTimeEvent, value); }
remove { this.RemoveHandler(ReportTimeEvent, value); }
}