WPFAQS - Routed Events in WPF

WPFAQS – is a series on WPF frequently asked questions (FAQS). Today we will discuss about “Routed Events” in WPF with some examples.

WPFAQS(005) – What are “Routed Events”? Give examples
Prerequisite/s – WPF, XAML, Custom and User Controls.

In my last WPFAQS on “Logical and Visual Trees”, I discussed very briefly about the routed events that they get routed based primarily on the visual tree. In today's post I’ll discuss them in a bit detail. A routed event is part of the publish-subscribe mechanism defined in the WPF event mechanism and is no different than the ordinary events accept the routed events are CLR events and get routed based on the “routing strategy” defined while compositing the visual tree of the elements/controls and needs some sort of special kind of registration. There are three types of routing strategy, Bubble, Tunnel, or Direct.

RoutedEvents2

The event that is initiated from the source element and travels or “bubbles” upward through the elements visual tree until it reaches root (typically a page or a window) has a bubbling strategy is a bubble event. While the tunnel events travels in the reverse direction. They start at the root element and traverse down the visual tree until they are handled by the event generating source. The direct events are like normal events defined as delegates in the .NET Framework and you hook them up with some event-handler using += operator or so, and they are similar to WinForms Events. The obvious question is, what’s the purpose of these bubbling and tunneling strategies??? Here is why – Most of the controls like “Buttons” have a long composition of visual tree, and there is a possibility that when you click on them, you might clicked some child, like “ButtonChrome” in case of a “Button” that is well below the hierarchy. So what happens is the WPF event routing system bubbles/tunnels the event to/from the source, that it can be handled properly, and that's why these events are called routed events.

 Registration of Routed Events and their usage:

Lets take a look at the relevant classes of the WPF Routed Event Framework:

RoutedEvents

A routed event is basically an instance of the “RoutedEvent” class shown above and registered with WPF event system using “EventManager” class’s Static member “RegisterRoutedEvent”. Here is a typical example code of registering an event named “ExecuteMe”.

   1:  public partial class GlassButtonControl : Button
   2:      {
   3:          // Lazy, will be called once, when this class is accessed
   4:          public static readonly RoutedEvent ExecuteMeEvent;
   5:   
   6:          static GlassButtonControl()
   7:          {
   8:              ExecuteMeEvent = EventManager.RegisterRoutedEvent("ExecuteMe",
   9:                          RoutingStrategy.Bubble,
  10:                          typeof(RoutedEventHandler),
  11:                          typeof(GlassButtonControl));
  12:          }
  13:   
  14:          // Provide CLR accessors for the event
  15:          public event RoutedEventHandler ExecuteMe
  16:          {
  17:              add { AddHandler(ExecuteMeEvent, value); }
  18:              remove { RemoveHandler(ExecuteMeEvent, value); }
  19:          }
  20:   
  21:          public static void Test()
  22:          {
  23:              GlassButtonControl glassButton = new GlassButtonControl();
  24:              // glassButton.ExecuteMe += new RoutedEventHandler(glassButton_ExecuteMe);            
  25:              glassButton.AddHandler(GlassButtonControl.ExecuteMeEvent, 
  26:                  new RoutedEventHandler(glassButton_ExecuteMe));
  27:          }
  28:   
  29:          static void glassButton_ExecuteMe(object sender, RoutedEventArgs e)
  30:          {
  31:              throw new NotImplementedException();
  32:          }
  33:      }

The “RoutedEvent” instance is usually a public static readonly class level instance registers using EventManager.RegisterRoutedEvent and thus "owns" the routed event. In order to create handlers for them, typically we create backing and connection mechanism also called “wrapper” event, “ExecuteMe” getter and setter, the same way we create a dependency property  wrappers while registering the property with the WPF property system.  For example take a look at the above code under Test() method lines 21-27.

Lets take another example, this is a window that contains only one button, named “TestButton”

RoutedEvents4 and here is the “XAML” for it –

   1:  <Window x:Class="WpfTestApp.Window1"
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:      Title="Test Window" Height="75" Width="200">
   5:      <Grid>
   6:          <Button Name="TestButton" Click="TestButton_Click">Click Me</Button>
   7:      </Grid>
   8:  </Window>

and if you spy on the auto code generated for this XAML, it looks like this:

   1:          void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
   2:              switch (connectionId)
   3:              {
   4:              case 1:
   5:              this.TestButton = ((System.Windows.Controls.Button)(target));
   6:              
   7:              #line 6 "..\..\Window1.xaml"
   8:              this.TestButton.Click += 
   9:                  new System.Windows.RoutedEventHandler(this.TestButton_Click);
  10:              
  11:              #line default
  12:              #line hidden
  13:              return;
  14:              }
  15:              this._contentLoaded = true;
  16:          }

If you look closely at the line 8-9 above, you will see that the Click is “RoutedEventHandler” and the subscription is done the same way as we used to do in the regular event. One thing is important that behind the scene it actually calls the AddHandler, with a routing strategy of “RoutingStrategy.Bubble”, and that’s the default strategy. Lets take a closer look at the code behind of handling this routing event, “Click” –

   1:  namespace WpfTestApp
   2:  {
   3:      /// <summary>
   4:      /// Interaction logic for Window1.xaml
   5:      /// </summary>
   6:      public partial class Window1 : Window
   7:      {
   8:          public Window1()
   9:          {
  10:              InitializeComponent();
  11:          }
  12:   
  13:          private void TestButton_Click(object sender, 
  14:              RoutedEventArgs e)
  15:          {
  16:              e.Handled = true;
  17:          }
  18:      }
  19:  }

RoutedEvents5

You can also verify the “RoutingStrategy” for it by putting a breakpoint some where in the event handler, as shown above.

One other very powerful concept is introduced in WPF is like “Attached Properties”, you can also define “Attached Events”. So what does it mean? It means that there is a possibility that you might need to handle events somewhere else in the tree hierarchy besides the control itself and provides more flexibility in where you hook up your event handlers. As an example, lets change the XAML to something like this:

   1:  <Window x:Class="WpfTestApp.Window1"
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:      Title="Test Window" Height="75" Width="200">
   5:      <Grid x:Name="RootGrid" ButtonBase.Click="TestButton_Click">
   6:          <Button Name="TestButton">Click Me</Button>
   7:      </Grid>
   8:  </Window>

So what we did, we took the Click handler to the parent in the hierarchy – and if you spy on it, by looking at the auto-generated code, you’ll see some thing like this: -

   1:         void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
   2:              switch (connectionId)
   3:              {
   4:              case 1:
   5:              this.RootGrid = ((System.Windows.Controls.Grid)(target));
   6:              
   7:              #line 5 "..\..\Window1.xaml"
   8:              this.RootGrid.AddHandler(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, 
   9:                  new System.Windows.RoutedEventHandler(this.TestButton_Click));
  10:              
  11:              #line default
  12:              #line hidden
  13:              return;
  14:              case 2:
  15:              this.TestButton = ((System.Windows.Controls.Button)(target));
  16:              return;
  17:              }
  18:              this._contentLoaded = true;
  19:          }

lines 8-9, call’s the “Grid’s” AddHandler to register the ClickEvent. and here is the output of when we put a breakpoint in the handler :

RoutedEvents6

You can see that the event is again of  RoutedEvent type of “ButtonBase.Click” and the strategy is of “Bubble” type.

Lets take another scenario, lets put the handler on the Grid as well as the source button itself, lets see the outcome of it. Also I will explain what happens when i put “e.Handled=true”. Here is the example XAML

RoutedEvents7

and here is auto generated code for it :

RoutedEvents8

The click event is subscribed on two locations as shown above, obviously two events are generated, when you click the button. But i suppressed one by setting “e.Handled = true” in the source one. Note if you dont set this on the source, that is the button’s one then two events will be generated. Here is the code for it

   1:  namespace WpfTestApp
   2:  {
   3:      /// <summary>
   4:      /// Interaction logic for Window1.xaml
   5:      /// </summary>
   6:      public partial class Window1 : Window
   7:      {
   8:          public Window1()
   9:          {
  10:              InitializeComponent();
  11:          }
  12:   
  13:          private void TestButton_Click(object sender, 
  14:              RoutedEventArgs e)
  15:          {
  16:   
  17:          }
  18:   
  19:          private void TestButton_Click_1(object sender, RoutedEventArgs e)
  20:          {
  21:              e.Handled = true;
  22:          }
  23:      }
  24:  }

If you look at the line-21, it means to inform the WPF routing system, that there is now no need of generating the event any more, its already handled. For more details on “Routed Events” take a look at MSDN documentation, here is the link for it “Routed Events Overview”.

That's all for now folks and will discuss another FAQS on WPF Command Routing and Commands/Commands Binding infrastructure, see you then. Look forward to your feed-back. enjoy :)

 

If you enjoyed reading this blog, leave your valuable feedback and consider subscribing to the RSS feed. You can also subscribe to it by email. Also, you can follow me on Twitter. Thank you!

Comments (13) -

How to Lose Weight Fast
4/7/2016 6:36:40 PM #

I all the time emailed this website post page to all my contacts, for the reason that if like to read it then my contacts will too.

coupons for babies r us in store
4/10/2016 4:07:02 PM #

Thanks designed  coupons for babies r us in store - http://www.cadmarket.ru/bitrix/rk.php?goto=http://smo9.co.in/youtube/helpful-tips-and-tricks-to-your-babies-r-us-coupon-savings/  sharing such a pleasant thought, piece of writing is good, thats why i have read it fully

Jesse
7/1/2016 2:25:42 PM #

At my other faculty, the workers did not have the capability of coping with folks with autism.

rolex replica
9/9/2016 5:41:04 AM #

Not alone did Wendo and the http://www.lblp.co.uk breitling replica aggregation authority assimilate their advance in http://www.replicasonline.co.uk replica watches uk a actual aggressive Chase 5 of our all-around series, but was 22nd over the band in the RSHYR out of the 77 actual finishers and was placed 9th all-embracing afterwards affliction in the IRC Analysis 2 Class.Wendo’s aggregation were aswell awarded the Stormhoek Social Spirit Award, absitively by accessible vote; the http://www.toprolexsreplicauk.co.uk rolex replica additional after time they accept accustomed the accolade.

Samual C. Niblett
10/6/2016 7:06:32 AM #

Thank you for the informative post. Look forward to hearing more in the future.

hotels near me
11/14/2016 1:20:12 PM #

Have you ever thought about including a little bit more than just your articles? I mean, what you say is valuable and everything. Nevertheless think of if you added some great photos or video clips to give your posts more, "pop"! Your content is excellent but with pics and videos, this blog could definitely be one of the very best in its field. Awesome blog!  My blog:  http://hotelsnearme.website/ - http://hotelsnearme.website/

paypal login
12/1/2016 4:47:30 PM #

Hi there colleagues, nice piece of writing and good arguments commented at this place, I am in fact enjoying by these.  My website:  paypal login - www.dobepups.com/.../

My brother recommended I may like this blog. He used to be totally right. This submit truly made my day. You cann't imagine simply how so much time I had spent for this info! Thank you!  My website:  http://hireaholidayhome.co.uk/author/faustolott7/ - http://hireaholidayhome.co.uk/author/faustolott7/

www.yahoo.com login
12/13/2016 5:04:13 PM #

May I simply just say what a comfort to discover someone that really knows what they are discussing over the internet. You certainly realize how to bring an issue to light and make it important. More people need to look at this and understand this side of your story. It's surprising you aren't more popular given that you definitely have the gift.  My my site:  www.yahoo.com login - labotech.lt/

netflix member sign in
12/16/2016 3:14:58 AM #

Quality articles or reviews is the important to interest the people to pay a visit the site, that's what this website is providing.  My my blog:  netflix member sign in - www.smartfone.com.co/

gmail.com login
12/17/2016 8:46:39 AM #

You need to take part in a contest for one of the best websites on the internet. I most certainly will recommend this website!  My my blog:  gmail.com login - www.wowmars.com.tw/

facebook login
12/20/2016 5:08:29 PM #

Hi, I do believe this is a great site. I stumbledupon it ;) I will come back yet again since I book marked it. Money and freedom is the best way to change, may you be rich and continue to guide other people.  My site:  facebook login - http://www.canhelps.com/author/louiegph80/

aol.com login
12/22/2016 7:39:15 PM #

Why people still use to read news papers when in this technological world the whole thing is existing on net?  My my blog:  aol.com login - http://loctung.com/component/k2/author/334924

amazon my account login
12/26/2016 10:09:01 PM #

I'm not sure exactly why but this web site is loading extremely slow for me. Is anyone else having this problem or is it a problem on  amazon my account login - expressvisa.cl/.../18319  end? I'll check back later and see if the problem still exists.

capital one banking online
12/29/2016 1:28:34 AM #

Oh my goodness! Incredible article dude! Thank you, However I am encountering difficulties with your RSS. I don't know the reason why I can't subscribe to it. Is there anybody else getting identical RSS issues? Anybody who knows the answer will you kindly respond? Thanks!!  My website:  www.irdes-eranet.eu/ - www.irdes-eranet.eu/

american express open
12/30/2016 8:54:03 AM #

Every weekend i used to pay a quick visit this site, as i want enjoyment, for the reason that this this web page conations really pleasant funny information too.  My my site:  american express open - rawadon.com/.../

Your way of telling all in this piece of writing is genuinely pleasant, every one be capable of simply be aware  bank of america online sign in banking - alsabbanest.com/  it, Thanks a lot.

capital one login credit card login
2/9/2017 11:58:08 PM #

Your style is very unique compared to other people I have read stuff from. I appreciate you for posting when you have the opportunity, Guess I will just book mark this page.  My site:  capital one login credit card login - http://www.justnotbuy.co.uk/author/ivyperdriau/

pnc login
2/24/2017 4:30:36 AM #

Patch Jobs is free for job-hunters, while employers pay a modest fee to publish positions and acquire an even bigger break when posting across multiple Patches.   pnc login - http://bazarcy.com/user/profile/581

aol mail login aol mail
2/24/2017 7:39:05 AM #

&#8221; In the Sender Filter section, choose how you need to block or filter emails.   aol mail login aol mail - http://baratillocusco.com/user/profile/282

fidelity login
2/25/2017 10:42:21 AM #

It is essential to note, however, that  fidelity login - http://kinoklasika.com/user/KennyGilchrist0/  still has a broad selection of annuity products on our platform to meet customers' savings and income needs.

suntrust online banking login
2/25/2017 7:37:11 PM #

Being in a position to share that moment on stage with Roxie meant everything to us, as she was recognized with the credit she deserves,� Reno said.   suntrust online banking login - http://thesafarihunter.com/author/annettaward/

bankofamerica.com sign in
3/1/2017 11:35:43 AM #

Hi there! I could have sworn I've been to this site before but after reading through some of the post I realized it's new to me. Anyways, I'm definitely happy I found it and I'll be book-marking and checking back often!   bankofamerica.com sign in - http://thinktoronto.ca/user/profile/502

aol.com login
3/6/2017 9:11:49 AM #

Since it had been one with the first major Internet agencies and email providers, a lot of users all in the world have.   aol.com login - drserapmutlu.com/

gmail.com login
3/8/2017 1:22:57 PM #

Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.   gmail.com login - http://daumoinongsan.com/user/profile/408

facebook profile pictures
3/8/2017 7:10:25 PM #

Hold about the "ALT" key and press "1" then "1" again in quick succession to obtain "&#9794;. Facebook&#039;s private message features certainly are a convenient way to obtain communications from friends which can be too long to your  facebook profile pictures - jtemp18.casample.co.za/.../282679  Wall or.

create itunes account
3/10/2017 10:14:10 PM #

Setting an MP3 as a possible i - Phone ring tone is often a fairly easy process that utilizes free software available for both Windows and. Navigate on the "File" menu without touching any keys around the keyboard.   create itunes account - http://www.spicyadz.in/user/profile/7235

yahoo mail sign in
3/11/2017 9:09:33 AM #

Go to "Users" menu visible on the top administrative bar and click on "User Manager.   yahoo mail sign in - vsu.am/.../

SlimNow
3/25/2017 12:05:22 AM #

Hurrah, that's what I was exploring for, what a information! existing here at this blog, thanks admin of this web site.

Trucos y guias
3/26/2017 6:04:33 AM #

 Ha habido momentos en las que me he distraido y otros bastante hartos  Revisa y ademas navega por mi web blog-  Trucos y guias - www.byasia.biz/.../netsoltrademark.php

Greetings from Colorado! I'm bored at work so I decided to browse your website on my iphone during lunch break. I really like the knowledge you provide here and can't wait to take a look when I get home. I'm amazed at how quick your blog loaded on my phone .. I'm not even using WIFI, just 3G .. Anyhow, excellent blog!

Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn't appear. Grrrr... well I'm not writing all that over again. Anyhow, just wanted to say fantastic blog!

loic
4/4/2017 4:27:14 AM #

After looking at a number of the blog posts on your blog, I honestly like your technique of blogging. I added it to my bookmark webpage list and will be checking back in the near future. Take a look at my web site as well and tell me how you feel.

Trucos
4/4/2017 11:40:28 AM #

 Me divierte sobradamente este titulo a pesar de todo los graficos son realmente tipicos  Hecha un vistazo y ademas visita mi blog;  Trucos - bluebreeze.com/.../netsoltrademark.php

citi cards pay online
4/6/2017 12:04:41 AM #

Each agent is certainly going to have a very different stance about this. You can double-click on the desktop icon to look at it or select it through the dock if you're using a Mac.   citi cards pay online - tdacademy.co.za/.../

icmp flood
4/7/2017 3:45:23 AM #

I am regular visitor, how are you everybody? This article posted at this website is truly good.

BHW
4/12/2017 2:48:50 AM #

You could certainly see your enthusiasm within the article you write. The arena hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

citicards no late fee
4/14/2017 2:47:12 PM #

Make sure you know the many rates you will be charged, not merely the rate under the very best circumstances. Set your Citibank bank card account online therefore you get having access to many facilities.   citicards no late fee - www.madreteresajoinville.org.br/

my aol email
4/15/2017 10:41:06 PM #

The ones technologies included, for model, the mouse, video conference meetings, word application, and hypertext.   my aol email - guiacomercialdobras.com.br/author/syreetahamm/

BHW
4/16/2017 3:25:06 PM #

I every time used to study paragraph in news papers but now as I am a user of net thus from now I am using net for posts, thanks to web.

pgcps gmail login
4/16/2017 6:37:26 PM #

, how it is possible to sign up which is go throughout the gmail registration process and exactly how the features on  pgcps gmail login - https://www.alansarionline.info/?q=node/137402 . We're thinking on how natural meats introduce these ideas.

facebook sign in
4/17/2017 10:35:46 AM #

Click with a username inside Pokes box to visit those's profile page. Click the "Customize" option and select "Only Me" through the menu that appears within the resulting box.   facebook sign in - http://pagebin.com/h3k7EMo2

Add comment