Events are not a new part to know about if you are working in Microsoft Technologies, but now when WPF has introduce a new concept called as Rounted Events, we will look into the same.
The main thing we should take care in Routed Events is about control's hierarchy. In WPF, a typical example of control's hierarchy is root level Window object, than Grid object and then the other controls which are resides on Grid Control.
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 The Button, The Label, The Gird or The Window.
Types of Routed Events :
- Direct Events
- Bubbling Events
- 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. Taking our Button control example, If Button is clicked, first it will raise Button_click event, then the Grid event and at last the Window Event.
The below picture will clear all your doubts:
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.
Let's take an example of the same to understand it better:
1. Open Visual Studio 2010 (I have VS 2010, you may use 2010 or whichever the version you have)
2. Create new WPF Application (I'm using VB.NET as the language)
3. Add a simple Text Box to the designer window.
4. Paste the below XAML Code to your Window:
Title="MainWindow" Height="350" Width="525"
<TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="TextBox1" VerticalAlignment="Top" Width="120" TextChanged="TextBox1_TextChanged"/>
5. Paste the below VB.NET Code to your source code file.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
MessageBox.Show("Event Raised By TextBox")
Private Sub Grid_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
MessageBox.Show("Event Raised By Grid")
Private Sub Window_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
MessageBox.Show("Event Raised By Window")
6. Press F5 to run.
7. Write something into the Text Box.
Thanks & Have Fun!!