自定義 DependencyProperty 與 RoutedEvent
阿新 • • 發佈:2018-08-15
click public 事件 clas 調用 wpf typeof t對象 模型 原文:自定義 DependencyProperty 與 RoutedEvent
//自定義依賴屬性 class MyBook : DependencyObject//依賴屬性必須派生自DependencyObject { public static readonly DependencyProperty BookNameProperty = DependencyProperty.Register("BookName", typeof(string), typeof(MyBook));//依賴屬性必須是靜態的DependencyObject對象 publicstring 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