//自定义依赖属性 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
原文:https://www.cnblogs.com/lonelyxmas/p/9478979.html