Oct 27, 2012

Routed Events in WPF

5 comments
Routed events are events which navigate up or down the visual tree acording to their RoutingStrategy. The routing strategy can be bubbling, tunneling or direct. You can hook up event handlers on the element that raises the event or also on other elements above or below it by using the attached event syntax: Button.Click="Button_Click".

Routed events normally appear as pair. The first is a tunneling event called PreviewMouseDown and the second is the bubbling called MouseDown. They don't stop routing if they reach an event handler. To stop routing then we have to set e.Handled = true; .

Routed events are very similar to dependency properties (though instead of the Property suffix, by convention, we use an Event suffix… though it is not required).  Also need to register a RoutedEvent in the static constructor, followed by a standard .NET event wrapper.  Same as for dependency properties, DO NOT put any logic in the event wrapper itself.



Routing Strategies:

Tunneling: This event is raised on the root element and navigates down to the visual tree until it reaches the source element or until the tunneling is stopped by marking the event as handled. By naming convention it is called Preview... and appears before corresponding bubbling event.

Bubbling: This event is raised on the source element and navigates up to the visual tree until it reaches the root element or until the bubbling is stopped by marking the event as handled. The bubbling event is raised after the tunneling event.

Direct: The event is raised on the source element and must be handled on the source element itself. This behavior is the same as normal .NET events.

Routing Event Handlers:

Event handlers for routed events follow the same syntax as traditional .NET events and share the same signature.  The first parameter, of type System.Object is a reference to the object to which the handler was attached to, whilst the second parameter is always a type extending System.Windows.RoutedEventArgs (or an instance of RoutedEventArgs), which exposes 4 very useful properties as mentioned below,
  • Handled: Gets or sets a value that indicates the present state of the event handling for a routed event as it travels the route.  

    OriginalSource: The original reporting source, before any possible System.Windows.RoutedEventArgs.Source adjustment made by class handling, which may have been done to flatten composited element trees.

    RoutedEvent: The System.Windows.RoutedEventArgs.RoutedEvent associated with thisSystem.Windows.RoutedEventArgs instance.

    Source: A reference to the object that raised the event. 


Creating And Raising Routed Event:

  1. Declare the static RoutedEvent as a field in your class
  2. Register the RoutedEvent in a static constructor
  3. Raise the event
 
    // Interaction logic for MainWindow.xaml
    public partial class MainWindow : Window
    {
        private static readonly RoutedEvent SimpleClickEvent;

        static MainWindow()
        {
            SimpleClickEvent = EventManager.RegisterRoutedEvent("SimpleClick", 
                RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MainWindow));
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        // The Standard .Net optional event wrapper
        // This is required if we want to register the event handler in XAML        
        public event RoutedEventHandler SimpleClick
        {
            add { AddHandler(SimpleClickEvent, value); }
            remove { RemoveHandler(SimpleClickEvent, value); }
        }
        
        // Raise the event. overidden from UIElement        
        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(SimpleClickEvent, this));
        }


Consuming Routed Event:

And following this, we can import the namespace, and register an event handler accordingly in XAML.

<Window x:Class="RoutedEventsExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
       
        xmlns:RoutedEventsExample="clr-namespace:RoutedEventsExample"
        RoutedEventsExample:MainWindow.SimpleClick="SimpleClickEventHandlingCode">
</Window>

Following is the event handler in code behind class(MainWindow.xaml.cs),
 
private void SimpleClickEventHandlingCode(Object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Implement logic as per your requirement here.", "Custom RoutedEvent Handling");
        }

That’s all there is to it.

If you feel this is helpful or you like it, Please share this using share buttons available on page.

5 comments :

  1. This is so essential post. This information helps them who are new bloggers. Thanks for helpful post for us.
    access Mp3skull in UK

    ReplyDelete
  2. Useful post; I am doing custom routed events in my wpf app and this actually was just what I needed. Thanks Naviya.

    ReplyDelete
  3. Anonymous11/17/2016

    whose the dumb ass cock sucking unit inch goat humper who posted this peice of crap rofl

    ReplyDelete
  4. Anonymous11/17/2016

    Hey nice copy and paste article rofl

    ReplyDelete