WPF附加事件定义


路由事件的宿主都是些拥有可视化实体的界面元素,而附加事件则不具备显示在用户界面上的能力。添加和移出附件事件的两个方法命名约定:

1、为目标UI元素添加附加事件侦听器的包装器是一个名为 Add*Handler的public static方法。星号代表事件名称,与注册事件时的名称一致。

2、解除UI元素对附加事件侦听的包装器是名为Remove*Handler的public static方法,星号也是事件名称。


代码如下:

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }

    public static readonly RoutedEvent NameChangedEvent = EventManager.RegisterRoutedEvent("NameChanged", 
        RoutingStrategy.Bubble,
        typeof(RoutedEventHandler),
        typeof(Student));

    public static void AddNameChangedHandler(DependencyObject d, RoutedEventHandler h)
    {
        UIElement element = d as UIElement;
        if (element != null) element.AddHandler(Student.NameChangedEvent, h);
    }

    public static void RemoveNameChangedHandler(DependencyObject d, RoutedEventHandler h)
    {
        UIElement element = d as UIElement;
        if (element != null) element.RemoveHandler(Student.NameChangedEvent, h);
    }
}


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

猜你喜欢

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