Events in WPF – Routed Events in WPF

The routed event architecture in WPF allows for an event that originates in one control to be raised by another control in the containment hierarchy.

There are three types of routed events: direct, bubbling, and tunneling.

  • Direct events

a direct event is raised only by the control in which it originates. Because other controls in the control containment hierarchy do not raise these events, there is no opportunity for any other control to provide handlers for these events. E.g. MouseLeave

  • Bubbling events:

Originates in control that raises event and can be handled in any control in parent element. E.g. MouseDown

  • Tunnelling events:

The tunnelling event always is raised before its corresponding bubbling event, thus allowing higher-level controls in the visual tree to handle the event.Each tunneling event shares its instance of event arguments with its paired bubbling event

RoutedEventArgs

This class is part of event signature and provides additional info about event like whether its handled, whats source, object that raised event e.g.

Way to attach event handler

Preferred way is put it in XAML e.g Click=”OnClicked”

Way to attach event handler

Event can be handled in control which can not raise that event e.g. Grid can have Button.Click=”OnClick” defined. Which will handle all button events in that grid.

wpf-routed-event-overview

wpf-routed-event-overview

EventManager

It’s a static class that manages registration of all routed events of WPF. You can get all routed events registered within application or for specific control. You can register class as well as instance level event handler.

How to define routed event

  1. Define static and readonly instance of RoutedEvent
  2. Write wrapper to expose traditional event
  3. Create your own RoutedEventArgs class and delegate that takes it as param
  4. Use EventManager to register the new event in the constructor of the class that owns this event. You must provide the name of the event, the routing strategy (direct, tunneling, or bubbling), the type of delegate that handles the event, and the type of the class that owns it.

How to raise Routed event

  1. Create instance of RoutedEventArgs
  2. Pass it to RaiseEvent method.

Create class level event handler:

  1. Create static method to handle event so that you can handle event for all instances and supress them
  2. Create delegate in static constructor
  3. Also RegisterClassEventHandler in same constructor

Application level events

Application class can handle startup, activated ,deactivated, exit and dispatcher unhandled kind of events. These should be handled in standard .net way.

Leave a Reply

Your email address will not be published. Required fields are marked *