自定义 DependencyProperty 与 RoutedEvent
Posted lonelyxmas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义 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)引发普通事件 } }
以上是关于自定义 DependencyProperty 与 RoutedEvent的主要内容,如果未能解决你的问题,请参考以下文章
设置绑定到 WPF 用户控件内的自定义 DependencyProperty
根据自定义 DependencyProperty 设置控件的可见性
自定义用户控件的 DependencyProperty 绑定未在更改时更新
只能在 DependencyObject 的 DependencyProperty 上设置“绑定”