#604 – Defining a New Routed Event
July 17, 2012 1 Comment
You can create a new routed event in your own class, typically in a control. Here, we define a new event named RightDrag in the MyButton class, which derives from Button.
Define a static object of type RoutedEvent.
public static readonly RoutedEvent RightDragEvent;
In the static constructor, register the event and set the RoutedEvent object.
static MyButton() { RightDragEvent = EventManager.RegisterRoutedEvent("RightDrag", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton)); }
Define a CLR event of type RoutedEventHandler or one of its subtypes. Call the AddHandler/RemoveHandler methods.
public event RoutedEventHandler RightDrag { add { AddHandler(RightDragEvent, value); } remove { RemoveHandler(RightDragEvent, value); } }
Add a helper method to fire the event.
protected virtual void OnRightDrag() { RoutedEventArgs evargs = new RoutedEventArgs(RightDragEvent, this); RaiseEvent(evargs); }
Finally, fire your event when appropriate.
void MyButton_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { if (e.RightButton == MouseButtonState.Pressed) OnRightDrag(); }