×

iFour Logo

Understanding Routed Events in WPF

Kapil Panchal - February 19, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Understanding Routed Events in WPF

What are routed events in WPF?


A routed event is a type of event that, in an element, a tree has multiple listeners and that is handle by the routed events. A routed event is a basically CLR event and it is supported by an instance of the Routed Event class.

In the WPF application, they contain multiple elements some elements are declared in XAML, and some elements are declared in code, and these all elements are related to each other in a tree relationship.

Tree Structures


To identify the relationship between UI elements in a WPF application, there are two object tree structures.

1. Logical Tree Structure

What we are created in XAML represents the logical tree structure. You can see the below logical tree structure.

                    
                    
                    
                                      

2. Visual Tree Structure

Visual tree structure represents the structure of a visual object by the Visual Base Class. Visual tree structures are used to render the visual layouts and objects. In the routed events mostly, visual tree structures are used instead of a logical tree structure. You can see the visual tree structure of your project when you compile and run your program.

There have three routing strategies which are as follows.

  • Direct Event
  • Bubbling Event
  • Tunnel Event
Direct Event

This event is raised by the element in which the event is organized. A standard CLR event can be used in Event Setters and Event Triggers within the style of your custom control. MouseEnter event is the best example of a direct event.

Bubbling Event

A bubbling event starts with the element where an event is organized and it can travel up the visual tree to the topmost element in the visual tree.

Tunnel Event

Tunnel events can invoke the root element tree and travel down the visual tree to all the children nodes.

Let’s see the simple route example.

MainWindow.xaml
							
							
							
							
							
							
							
													  
										  

In this example, we can add click event of a window, stackpanel, and button we can change the text of text block when a button is clicked.

MainWindow.xaml.cs
 
		using System;
		using System.Collections.Generic;
		using System.Linq;
		using System.Text;
		using System.Threading.Tasks;
		using System.Windows;
		using System.Windows.Controls;
		using System.Windows.Data;
		using System.Windows.Documents;
		using System.Windows.Input;
		using System.Windows.Media;
		using System.Windows.Media.Imaging;
		using System.Windows.Navigation;
		using System.Windows.Shapes;
		namespace RoutedEvents
		{
			public partial class MainWindow : Window
			{
				public MainWindow()
				{
					InitializeComponent();
				}
				private void Button_Click(object sender, RoutedEventArgs e)
				{
					textblock1.Text = "Button is Clicked";
				}
				private void StackPanel_Click(object sender, RoutedEventArgs e)
				{
					textblock2.Text = "Click event of StackPanel";
				}
				private void Window_Click(object sender, RoutedEventArgs e)
				{
					textblock3.Text = "Click event of Window";
				}
			}
		}
										  
Output

Azure vs AWS

Image: Before clicking the button

Azure vs AWS

Image: After clicking the button event

In WPF, you can stop the routed event at any particular level. For stopping routed events you need to set e.Handled = true;

 
		   private void StackPanel_Click(object sender, RoutedEventArgs e)
			{
			  textblock2.Text = "Click event of StackPanel";
			   e.Handled = true;
			 }
										  

Azure vs AWS

Image: Example of stopping routed events

En you set e.Handler = true on specific control then this can be stopped all routing events after coming up that control.

 
Custom Routed Events

Below is the step to define custom routed events.

  • First, you need to declare and register your event with the help of RegisterRoutedEvent.
  • Three types of Routing strategy to specify the routing strategy (Direct, Tunnel, and Bubble).
  • Event handler provides.

Now, we can create an example of custom routed events.

Step: 1

Open Visual Studio and select the WPF project.

Azure vs AWS

Image: Create a WPF project

Step: 2

When your project is created, right-click solution explorer and select Add -> New Item -> Custom Control (WPF) and give the name.

When you click to Add button, you will see that two files are added one is a .cs file and the second is a Generic.xaml file.

Step: 3

Open Generic.xaml file and create a style for custom control.

Generic.xaml

Wants to Talk with Our Highly Skilled WPF Developer ?
Contact Now

Step: 4

In MyCustomControl class, we can create a click of a custom routed event for the custom control.


MyCustomControl.cs
		using System;
		using System.Collections.Generic;
		using System.Linq;
		using System.Text;
		using System.Threading.Tasks;
		using System.Windows;
		using System.Windows.Controls;
		using System.Windows.Data;
		using System.Windows.Documents;
		using System.Windows.Input;
		using System.Windows.Media;
		using System.Windows.Media.Imaging;
		using System.Windows.Navigation;
		using System.Windows.Shapes;
		namespace RoutedEvents
		{
			public class MyCustomControl : Control
			{
				static MyCustomControl()
				{
					DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
				}
				public override void OnApplyTemplate()
				{
					base.OnApplyTemplate();
					var button = GetTemplateChild("PART_Button") as Button;
					if (button != null)
						button.Click += Button_Click;
				}
				void Button_Click(object sender, RoutedEventArgs e)
				{
					RaiseClickEvent();
				}
				public static readonly RoutedEvent ClickEvent =
				   EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble,
				   typeof(RoutedEventHandler), typeof(MyCustomControl));
				public event RoutedEventHandler Click
				{
					add { AddHandler(ClickEvent, value); }
					remove { RemoveHandler(ClickEvent, value); }
				}
				protected virtual void RaiseClickEvent()
				{
					RoutedEventArgs args = new RoutedEventArgs(MyCustomControl.ClickEvent);
					RaiseEvent(args);
				}
			}
		}
			

Now, we just need to add a message box when the user clicks the button.


MainWindow.xaml.cs
		public partial class MainWindow : Window
			  {
				  public MainWindow()
				  {
					  InitializeComponent();
				  }
				  private void MyCustomControl_Click(object sender, RoutedEventArgs e)
				  {
					  MessageBox.Show("Custom Routed Event of Custom Control!!");
				  }
			  }
MainWindow.xaml

Azure vs AWS

Image: Before clicking a button0

Azure vs AWS

Image: A custom routed event of custom control

Conclusion


In this blog, we have learned about the basic concepts of routing events. Hence, you can also create your own routed events on your custom class with some support like specialization event data classes and delegates.

Understanding Routed Events in WPF What are routed events in WPF? A routed event is a type of event that, in an element, a tree has multiple listeners and that is handle by the routed events. A routed event is a basically CLR event and it is supported by an instance of the Routed Event class. In the WPF application, they contain multiple elements some elements are declared in XAML, and some elements are declared in code, and these all elements are related to each other in a tree relationship. Tree Structures To identify the relationship between UI elements in a WPF application, there are two object tree structures. 1. Logical Tree Structure What we are created in XAML represents the logical tree structure. You can see the below logical tree structure. 2. Visual Tree Structure Visual tree structure represents the structure of a visual object by the Visual Base Class. Visual tree structures are used to render the visual layouts and objects. In the routed events mostly, visual tree structures are used instead of a logical tree structure. You can see the visual tree structure of your project when you compile and run your program. There have three routing strategies which are as follows. Direct Event Bubbling Event Tunnel Event Direct Event This event is raised by the element in which the event is organized. A standard CLR event can be used in Event Setters and Event Triggers within the style of your custom control. MouseEnter event is the best example of a direct event. Bubbling Event A bubbling event starts with the element where an event is organized and it can travel up the visual tree to the topmost element in the visual tree. Tunnel Event Tunnel events can invoke the root element tree and travel down the visual tree to all the children nodes. Let’s see the simple route example. MainWindow.xaml In this example, we can add click event of a window, stackpanel, and button we can change the text of text block when a button is clicked. Read More: What Is Treeview In Wpf? MainWindow.xaml.cs   using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RoutedEvents { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { textblock1.Text = "Button is Clicked"; } private void StackPanel_Click(object sender, RoutedEventArgs e) { textblock2.Text = "Click event of StackPanel"; } private void Window_Click(object sender, RoutedEventArgs e) { textblock3.Text = "Click event of Window"; } } } Output Image: Before clicking the button Image: After clicking the button event In WPF, you can stop the routed event at any particular level. For stopping routed events you need to set e.Handled = true;   private void StackPanel_Click(object sender, RoutedEventArgs e) { textblock2.Text = "Click event of StackPanel"; e.Handled = true; } Image: Example of stopping routed events En you set e.Handler = true on specific control then this can be stopped all routing events after coming up that control.   Custom Routed Events Below is the step to define custom routed events. First, you need to declare and register your event with the help of RegisterRoutedEvent. Three types of Routing strategy to specify the routing strategy (Direct, Tunnel, and Bubble). Event handler provides. Now, we can create an example of custom routed events. Step: 1 Open Visual Studio and select the WPF project. Image: Create a WPF project Step: 2 When your project is created, right-click solution explorer and select Add -> New Item -> Custom Control (WPF) and give the name. When you click to Add button, you will see that two files are added one is a .cs file and the second is a Generic.xaml file. Step: 3 Open Generic.xaml file and create a style for custom control. Generic.xaml Wants to Talk with Our Highly Skilled WPF Developer ? Contact Now See here Step: 4 In MyCustomControl class, we can create a click of a custom routed event for the custom control. MyCustomControl.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RoutedEvents { public class MyCustomControl : Control { static MyCustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); } public override void OnApplyTemplate() { base.OnApplyTemplate(); var button = GetTemplateChild("PART_Button") as Button; if (button != null) button.Click += Button_Click; } void Button_Click(object sender, RoutedEventArgs e) { RaiseClickEvent(); } public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyCustomControl)); public event RoutedEventHandler Click { add { AddHandler(ClickEvent, value); } remove { RemoveHandler(ClickEvent, value); } } protected virtual void RaiseClickEvent() { RoutedEventArgs args = new RoutedEventArgs(MyCustomControl.ClickEvent); RaiseEvent(args); } } } Now, we just need to add a message box when the user clicks the button. MainWindow.xaml.cs public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void MyCustomControl_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Custom Routed Event of Custom Control!!"); } } MainWindow.xaml Image: Before clicking a button0 Image: A custom routed event of custom control Conclusion In this blog, we have learned about the basic concepts of routing events. Hence, you can also create your own routed events on your custom class with some support like specialization event data classes and delegates.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...