自定义 DependencyProperty 与 RoutedEvent

本文介绍如何在WPF中自定义DependencyProperty与RoutedEvent。通过具体的代码示例展示了依赖属性的定义、注册及包装的过程,同时讲解了路由事件的定义、注册和触发方法。
原文: 自定义 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)引发普通事件
        }
    }

 

posted on 2018-08-15 00:08 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/9478979.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值