WPF自定义事件

一、定义事件的参数类

public class MyEventArge:RoutedEventArgs 
{} 

 

二、定义和注册事件

public static readonly RoutedEvent MyRoutedEvent = EventManager.RegisterRoutedEvent( 
   "MyRoutedEvent"RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UserControl1));

或者

public static readonly RoutedEvent MyRoutedEvent;

static UserControl1(){

  MyRoutedEvent = EventManager.RegisterRoutedEvent( 
     "MyRoutedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UserControl1));

}

 

RoutingStrategy -- 事件的类型:直接 、冒泡和隧道

Direct :直接路由,事件不再传递

Bubble:冒泡路由,由起源传递到root节点

Tunnel:隧道路由,由root传递到起源

 

三、定义传统事件包装(traditional event wrapper)

public event RoutedEventHandler MyEvent{

  add{ base.AddHandler(MyRoutedEvent , value); }

      remove{ base.removeHandler(MyRoutedEvent , value);}

}

 

四、绑定Handler

UserControl1.MyEvent += delegate{MessageBox.Show("MyEvent ");}

 

五、触发事件

RaiseEvent(new MyEventArge(UserControl1.MyEvent, this));

你可能感兴趣的:(WPF)