Wednesday, 1 May 2013

Types of Routed Events in WPF

Types of Routed Events in WPF
 
The concept of Routed Events comes into the picture when we want to handle an event, that is originated from some other control in the hierarchy.  Say for example if any user clicks the button control, that event which is normally a button_click event, can be raised by button, label, gird or window.
 
Types of Routed Events:
 
WPF defines most routed events in pairs - one tunnelling and the other bubbling.
 
1. Direct Events
2. Bubbling Events
3. Tunneling Events
 
1.  Direct Events:
 
Direct Events are very well known to .NET people who has worked on standard .NET controls.  A direct event get raised by the control itself. Say for example button_click event which got raised by the button control itself.
 
2.  Bubbling Events:
 
Bubbling events are first raised by the control and then are raised by the controls in that control's hierarchy. Say in a window, we have a grid and in that we have a button control. Now if button is clicked, first it will raise button_click event, then the grid event and at last the window event.
 
3.  Tunneling Events:
 
The Tunneling Events are the opposite of the bubbling events as they are raised first by the root element in the hierarchy and then by the child elements. Same as our previous example, first window event will get raised, followed by the grid event and at last the button_click event.
 
The tunnelling event name always begins with 'Preview' and is raised first. This gives parents the chance to see the event before it reaches the child. This is followed by the bubbling counterpart. In most cases, you will handle only the bubbling one.
 
Example of Routed Events
 
Routed Events provide the ability for different controls in the element tree to react to events.
For instance, if we have a Window containing a StackPanel containing a Button and someone presses the mouse key on the button, the events will be fired in this order:
 
PreviewMouseDown on Window
PreviewMouseDown on StackPanel
PreviewMouseDown on Button
MouseDown on Button
MouseDown on StackPanel
MouseDown on Window
 
Example with code
 
XAML file:
 
<Grid Button.Click="Grid_Click">
    <StackPanel Button.Click="StackPanel_Click">
        <Button Content="Click Me!" Height="35" Width="150"
        Margin="5" />
    </StackPanel>
</Grid>
 
CodeBehind file:
 
private void StackPanel_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Stackpanel");
}
 
private void Grid_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Grid");
}
 
Now when button is clicked, following messages will appear in sequence
Stackpanel
Grid

No comments:

Post a Comment