Although Silverlight has support internally for routed events it does not provide a means for developers to create their own. To fill this gap DevComponents has implemented a light weight version of the routed event which is modeled on the Silverlight/Wpf versions and behaves the same. Routed events are implemented in the DevComponents.Silverlight.Controls.Eventing namespace defined in DevComponents.Silverlight.Controls.dll and are public so you are free to use them for your own events if you choose.

The objects defined in the DevComponents.Silverlight.Controls.Eventing namespace are:

  • EventManagerEx: exposes static and extension methods for working with DevComponents routed events.
  • RoutedEventEx:  definition of the DevComponents Routed Event.
  • RoutedEventHandlerEx: delegate for Routed Events.
  • RoutedEventArgsEx: event arguments for RoutedEventHandlerEx
  • RoutingStragety: enumeration to indicate how event notification is routed through the visual tree. Possible values are Bubble, Direct and Tunnel.

Defining a Routed Event

The same pattern for creating routed events in Wpf is used here. First, the routed event is defined as a static field of the containing class using the EventManager. By convention, the name of the static field is the same as the event name, with the word "Event" appended to it. Second, define a regular Clr event so clients can use the event as they would for any other Clr event. For example, to define a routed event named "IsSelectedChanged" in a class named AppointmentView use the following:

/// <summary>
/// Using DevComponents Routed event for IsSelectedChanged.
/// </summary>
public static readonly RoutedEventEx IsSelectedChangedEvent =
    EventManagerEx.RegisterRoutedEvent("IsSelectedChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandlerEx), typeof(AppointmentView));
/// <summary>
/// Event which is raised when the value of IsSelected changes. 
/// This is a DevComponents routed event. The routed event has a RoutingStragety of Bubble.
/// </summary>
public event RoutedEventHandlerEx IsSelectedChanged
    add { this.AddHandler(IsSelectedChangedEvent, value); }
    remove { this.RemoveHandler(IsSelectedChangedEvent, value); }

To fire the event, use the RaiseEvent extension method, like so:

RoutedEventArgsEx args = new RoutedEventArgsEx(IsSelectedChangedEvent, this);

Handling a Routed Event

And to handle the event, use the AddHandler extension method, like this:

    new RoutedEventHandlerEx(HandleAppointmentViewSelectedChanged));

Here is the event handler method:

private void HandleAppointmentViewSelectedChanged(object sender, RoutedEventArgsEx e)
    // Do something

Related posts:

  1. Commanding
  2. Silverlight Schedule Control Quick Start Guide
  3. Typed Data Templates
  4. Dynamic Resources
  5. Managing Color Theme and Re-Using Resources