自定义路由事件

自定义路由事件大体上可分为三个步骤:
1、声明并注册路由事件;
2、为路由事件添加CLR事件包装;
3、创建可以激发路由事件的方法。

主要的示例代码如下:
public class TimeButton : Button
{
    /// <summary>
    /// 声明并注册路由事件。
    /// </summary>
    public static readonly RoutedEvent ReportTimeEvent = EventManager.RegisterRoutedEvent("ReportTime", 
        RoutingStrategy.Bubble, 
        typeof(EventHandler<ReportTimeEventArgs>), 
        typeof(TimeButton));

    /// <summary>
    /// CLR事件包装器。
    /// </summary>
    public event RoutedEventHandler ReportTime
    {
        add { this.AddHandler(ReportTimeEvent, value); }
        remove { this.RemoveHandler(ReportTimeEvent, value); }
    }

    /// <summary>
    /// 激发路由事件,借用Click事件的激发方法。
    /// </summary>
    protected override void OnClick()
    {
        base.OnClick();

        ReportTimeEventArgs args = new ReportTimeEventArgs(ReportTimeEvent, this);
        args.ClickTime = DateTime.Now;
        this.RaiseEvent(args);
    }
}


发布了359 篇原创文章 · 获赞 211 · 访问量 94万+

猜你喜欢

转载自blog.csdn.net/gjysk/article/details/38611071