码迷,mamicode.com
首页 > 其他好文 > 详细

自定义 DependencyProperty 与 RoutedEvent

时间:2018-08-15 00:39:59      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:strategy   net   包装   tar   派生   event   route   raise   gis   

原文:自定义 DependencyProperty 与 RoutedEvent

    //自定义依赖属性
    class MyBook : DependencyObject//依赖属性必须派生自DependencyObject
    {
        public static readonly DependencyProperty BookNameProperty = DependencyProperty.Register("BookName", typeof(string), typeof(MyBook));//依赖属性必须是静态的DependencyObject对象
        public string BookName
        {
            get { return (string)GetValue(BookNameProperty); }
            set { SetValue(BookNameProperty, value); }
        }

        static MyBook()//静态构造函数
        {
            //BookNameProperty = DependencyProperty.Register("BookName", typeof(string), typeof(MyBook));
        }
    }
/*
 定义、注册、包装路由事件

WPF事件模型与WPF属性模型类似,与依赖项属性一样,路由事件由只读的静态字段表示,在静态构造函数中注册,并且通过一个标准的.NET事件定义进行包装*/
class MyButton : Button
    {
        //自定义路由事件
        public static readonly RoutedEvent HitEvent = EventManager.RegisterRoutedEvent("Hit", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
        public event RoutedEventHandler Hit
        {
            add { AddHandler(HitEvent, value); }
            remove { RemoveHandler(HitEvent, value); }
        }

        static MyButton()
        {
            //HitEvent = EventManager.RegisterRoutedEvent("Hit", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
        }

        public void RaiseRoutedEvent()
        {
            RoutedEventArgs routedEventArgs = new RoutedEventArgs(MyButton.HitEvent);
            //UIElement.RaiseEvent(RoutedEventArgs routedEeventArgs)方法
            this.RaiseEvent(routedEventArgs);//触发路由事件方法
        }

        //自定义普通事件
        //public delegate void EventHandler(object sender, EventArgs e);
        public event EventHandler SelectingButton;

        protected override void OnClick()
        {
            base.OnClick();

            RaiseRoutedEvent();//调用RaiseRoutedEvent()方法引发路由事件

            if (SelectingButton != null)
                SelectingButton(this, null);//调用SelectingButton(this, null)引发普通事件
        }
    }

 

自定义 DependencyProperty 与 RoutedEvent

标签:strategy   net   包装   tar   派生   event   route   raise   gis   

原文地址:https://www.cnblogs.com/lonelyxmas/p/9478979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!