WPF学习系列025: 3.3.1 路由事件的实现

来源:互联网 发布:手游美工 编辑:程序博客网 时间:2024/06/05 17:56

 

3.3.1 路由事件的实现

  1. 路由事件的类型为 System.Windows.RoutedEvent
  2. 所有的路由事件成员都必须是 publicstatic,并且有一个 Event 作为后缀。
  3. 路由事件通常通过调用 EventManager.RegisterRoutedEvent 静态方法创建。这个方法需要三个参数:
    1. 路由事件的名称
    2. 作为枚举值的事件的路由策略
    3. 事件处理程序的类型
    4. 路由事件的所有者类类型
  1. 路由事件定义完成后,最好添加 .NET 事件包装器(数据接口)实现对路由事件的访问,这样可以在 XAML 中用事件特性语法添加一个事件处理程序
  2. 在路由事件的事件包装器中,除了 AddHandler / RemoveHandler 调用外,不应该添加任何其它逻辑。

例如:

    public class Button : ButtonBase

    {

        // 路由事件

        public new static readonly RoutedEvent ClickEvent;

 

        static Button()

        {

            // 注册时间

            Button.ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Button));

        }

 

        // .NET事件包装器(可选)

        public new event RoutedEventHandler Click

        {

            add

            {

                this.AddHandler(Button.ClickEvent, value);

            }

            remove

            {

                this.RemoveHandler(Button.ClickEvent, value);

            }

        }

 

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)

        {

            base.OnMouseLeftButtonDown(e);

 

            // 触发事件

            this.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));

        }

    }

注意:

  1. AddHandlerRemoveHandler这两个方法都是继承自System.Windows.UIElement。通过调用这两个方法可以向一个适当的路由事件添加一个委托或者从路由事件移除一个委托。
  2. RaiseEvent也是继承自System.Windows.UIElement。它用来触发路由事件。
  3. public new static readonly RoutedEvent ClickEventpublic new event RoutedEventHandler Click 中关键字new的作用是有意隐藏ButtonBase中对ClickEventClick的定义。