WPF 自定义依赖属性与路由事件

  //自定义依赖属性
    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));
        }
    }
 
 
 
    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 RaiseHitEvent()
        {
            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();
 
            RaiseHitEvent();//调用RaiseHitEvent()方法引发路由事件
 
            if (SelectingButton != null)
                SelectingButton(this, null);//调用SelectingButton(this, null)引发普通事件
        }
    }

 

posted @ 2016-09-29 21:45  天涯海角路  阅读(205)  评论(0)    收藏  举报