WPF 路由事件
同级或上下级关系时,事件的响应者可订阅事件的发起者;通过委托,事件的响应者使用事件的处理器来做出交互响应。
多级关系时,路由事件的事件拥有者和事件的响应者之间则没有直接的显式订阅关系,事件的拥有者则只负责激发事件,事件将有谁响应它并不知道;事件的响应者则有事件的监听器,针对事件进行监听,当有此类事件传递至此事件响应者就使用事件处理器来相应事件并决定此事件是否继续传递。
路由事件沿逻辑树向上传递,按顺序响应。
var args = new ButtonRoutedEventArgs(MyRouteButton.RoutedClickEvent, this);
args.EventTime = DateTime.Now;
args.EventPublisher = nameof(事件的拥有者);
args.OtherArgs = 其他需要传递参数;
this.RaiseEvent(args);
public 事件的响应者()
{
InitializeComponent();
this.AddHandler(MyRouteButton.RoutedClickEvent, new RoutedEventHandler(RouteButton_Click));
}
private void RouteButton_Click(object sender, RoutedEventArgs e)
{
var ele = sender as FrameworkElement;
var arg = e as ButtonRoutedEventArgs;
if (arg.EventPublisher == nameof(事件的拥有者))
{
var data = arg.OtherArgs as DeliveryConfigDto;
// to do sth
e.Handled = true;
}
}
using System;
using System.Windows;
using System.Windows.Controls;
/// <summary>
/// 自定义路由按钮
/// </summary>
class MyRouteButton : Button
{
/// <summary>
/// 声明和注册路由事件
/// </summary>
public static readonly RoutedEvent RoutedClickEvent = EventManager.RegisterRoutedEvent("RoutedClick", RoutingStrategy.Bubble, typeof(EventHandler<ButtonRoutedEventArgs>), typeof(MyRouteButton));
/// <summary>
/// CLR事件
/// </summary>
public event RoutedEventHandler RoutedClick
{
add { this.AddHandler(RoutedClickEvent, value); }
remove { this.RemoveHandler(RoutedClickEvent, value); }
}
/// <summary>
/// 借用Click事件激发路由事件
/// </summary>
protected override void OnClick()
{
// 保证原有功能正常使用
base.OnClick();
ButtonRoutedEventArgs args = new ButtonRoutedEventArgs(RoutedClickEvent, this);
args.EventTime = DateTime.Now;
args.EventPublisher = this.ToString();
// UIElement及其派生类
this.RaiseEvent(args);
}
}
/// <summary>
/// 路由按钮事件参数
/// </summary>
class ButtonRoutedEventArgs : RoutedEventArgs
{
public ButtonRoutedEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }
/// <summary>
/// 事件的发生时间
/// </summary>
public DateTime EventTime { get; set; }
/// <summary>
/// 事件的发布者
/// </summary>
public string EventPublisher { get; set; }
/// <summary>
/// 其他参数
/// </summary>
public object OtherArgs { get; set; }
}
属性附加事件
/// <summary>
/// 属性
/// </summary>
public bool Handled { get; set; }
/// <summary>
/// 附加事件
/// </summary>
public static readonly RoutedEvent HandledEvent = EventManager.RegisterRoutedEvent("Handled", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(事件的拥有者));
public 事件的拥有者()
{
InitializeComponent();
this.AddHandler(HandledEvent, new RoutedEventHandler(OnHandledEvent));
}
/// <summary>
/// 属性附加事件响应
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnHandledEvent(object sender, RoutedEventArgs e)
{
}