在上一篇博文中写到了内置路由事件, 其实除了内置的路由事件, 我们也可以进行自定义路由事件接下来我们一起来看一下 WPF 中的自定义路由事件怎么进行创建吧
创建自定义路由事件分为 3 个步骤:
1 声明并注册路由事件
2 利用 CLR 事件包装路由事件 (封装路由事件)
3 创建可以激发路由事件的方法
现在我们一起创建一个能够报告当前时间和当前位置信息的路由事件, 一起去控件里面游览一番现在开始创建自定义路由事件
一声明自定义路由事件
创建继承 RoutedEventArgs 类的派生类 ReportCurrentLocationEventArgs 用来携带时间和位置消息, ClickTime 属性是用来存储时间, CurrentLocation 属性是用来存放位置
二定义注册路由事件
我们用 EventManager.RegisterRoutedEvent 方法来注册的参数有 4 个代码如下:
- public static readonly RoutedEvent ReportCurrentLocationEvent =EventManager.RegisterRoutedEvent
- ("ReportCurrentLocation", RoutingStrategy.Bubble, typeof(EventHandler<ReportCurrentLocationEventArgs
- >), typeof(ButtonReportCurrentLocation));
第一个参数是路由事件的名称 Name
第二个参数是路由事件的传递方式, 有三种方式:
第一种是 Bubble 是冒泡模式, 这种模式是从触发点向上传递, 知道最外层
第二种是 Direct 就是传统的事件一样的, 不会通过元素树
第三种是 Tunnel 是预览模式 (隧道模式), 这和冒泡的相反, 向下传递
第三个参数是路由事件处理器类型, 传递的参数是自定义类
第四个参数是拥有这个路由事件的类型
三封装路由事件
CLR 事件的封装器, 不同于依赖属性的 GetValue 和 SetValue, 这里是利用 Add 和 Remove 两个函数来给路由事件分配事件处理器
- public event RoutedEventHandler ReportCurrentLocation
- {
- add { this.AddHandler(ReportCurrentLocationEvent, value); }
- remove { this.RemoveHandler(ReportCurrentLocationEvent, value); }
- }
四创建可以激发路由事件的方法
重写 OnClick 方法触发设定路由事件, 这是使用 RaiseEvent() 方法来触发
- protected override void OnClick()
- {
- base.OnClick();
- ReportCurrentLocationEventArgs args = new ReportCurrentLocationEventArgs(ReportCurrentLocationEvent, this);
- args.ClickTime = DateTime.Now;
- this.RaiseEvent(args);
- }
完整代码如下图:
在界面 XAML 中, 设计如下:
那么最后看一下事件处理器是怎样的
运行效果:
来源: https://www.cnblogs.com/fly-bird/p/8542761.html