#600 – Registering a Routed Event

When you implement a routed event in a class, you end up creating an instance of the RoutedEvent type.

Instead of explicitly creating the RoutedEvent instance, you create it indirectly by calling EventManager.RegisterRoutedEvent.  This method accepts some information about the routed event that you want to create and returns an instance of a RoutedEvent, which you typically store in a static field.  You typically register the event in your static constructor, or at the time that it is declared, so you end up having only one instance of the RoutedEvent, no matter how many instances of your class get created.

        // Define/create the routed event object
        public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ButtonBase));

RegisterRoutedEvent takes the following parameters:

  • name – the name of the event
  • routingStrategy – the routing strategy–tunneling, bubbling or direct
  • handlerType – the delegate type for event handlers
  • ownerType – the class type for the event’s owner

#599 – A Complete Example of a Routed Event

To help you understand how routed events in WPF work, it’s helpful to look at how they are implemented.  Here is all of the relevant code from the ButtonBase class for the Click event.

    public abstract class ButtonBase : ContentControl, ICommandSource
    {
        // Define/create the routed event object
        public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ButtonBase));

        // CLR event wrapper, adds/removes handlers
        public event RoutedEventHandler Click { add { AddHandler(ClickEvent, value); } remove { RemoveHandler(ClickEvent, value); } }

        // Method used internally to fire the Click event
        protected virtual void OnClick()
        {
            RoutedEventArgs newEvent = new RoutedEventArgs(ButtonBase.ClickEvent, this);
            RaiseEvent(newEvent);
        }
    }

Both the AddHandler and RaiseEvent methods are defined in UIElement.