Sunday, October 23, 2011

Events

Routed events is another concept introduced in WPF. It might sound as a big thing to learn to those who are new to WPF, but actually its a complex concept which is simple to understand.

By now we all know WPF's power of keeping controls within controls, example, image and label inside stackpanel inside button inside grid inside window. So we get a complete control hierarchy. Now say, you want to click on the button, so when you do it you actually click on the image or the label as they are placed above the button. So how to call Button_click? Second scenario, suppose you have 8-10 buttons on a grid and you want to handle all these button clicks by one event handler. How do you do it?

Enters Routed events. Routed events can be raised by multiple controls and handled by multiple handlers. There are 3 types of events:
  1. Direct Events
  2. Bubbling Events
  3. Tunneling Events
  •  Direct Events are similar to traditional .NET events.
  • Bubbling event is raised first in the control where it actually occurs and then it travels up in the containment hierarchy until it is handled. In the above example, first the event would be raised by image, then button, then grid and then window. So this event can be handled by any of these or may be all of these.
  • Tunneling events is opposite of bubbling events. Here the event is first raised by the topmost control and then it travels down to the control that originally raised the event. Tunneling events have Preview word in their beginning, example PreviewMouseDown, and are raised before their corresponding Bubbling event.
All the routed event handlers have RoutedEventArgs as argument. If one wants to stop the bubbling or tunneling of the event to indicate that it has been already handled, one can set the Handled property to true.

Creating a routed event is simple too. In WPF, just write <Button ... Click="button1_click" />. This will auto generate an event handler button1_click in code behind.

It is also possible for a control to handle an event which is not defined in it. Example, if you want the grid to handle button click events. This can be achieved through Attached events. To do so,

<Grid.... Button.Click="button1_click" >
    <Button ... />
</Grid>

I guess I made it simple to understand!!!



No comments:

Post a Comment