Routed Events creation in WPF


 

Hi. In my previous article I described what routed events are and today I’ll show you how you can create your own routed events.

Creation

Create user control and add the following code:

public partial class CustomUserControl { public static RoutedEvent OrderCompletedEvent = EventManager.RegisterRoutedEvent("OrderCompleted", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof(CustomUserControl)); public event RoutedEventHandler OrderCompleted { add { AddHandler(OrderCompletedEvent, value); } remove { RemoveHandler(OrderCompletedEvent, value); } } public CustomUserControl() { InitializeComponent(); } }

In this code I added two class members:

  1. Public static field OrderCompletedEvent
  2. CLR event OrderCompleted

I use EventManager.RegisterRoutedEvent method to register my event is WPF system and save retrieved RoutedEvent instance in static field named OrderCompletedEvent. It’s a general convention to name backing field for event with “Event” suffix.

Then I added normal CLR event named OrderCompleted which is essentially wrapper around routed event. This method uses inherited AddHandler and RemoveHandler methods to attach or detach event handler respectively.

Event Triggering

Open XAML for CustomUserControl and add one button with subscription for Click event:

<Button Content="Place order" Click="Button_Click"/>

In this method I will trigger OrderCompleted event:

private void Button_Click(object sender, RoutedEventArgs e) { var eventArgs = new RoutedEventArgs(OrderCompletedEvent); RaiseEvent(eventArgs); }

As you can see, to trigger routed event you just need to create RoutedEventArgs instance, pass it RoutedEvent instance and then call inherited RaiseEvent method.

And here is code which uses CustomUserControl and its OrderCompleted event:

<Window x:Class="RoutedEventsCreationSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:RoutedEventsCreationSample="clr-namespace:RoutedEventsCreationSample" Title="MainWindow" Height="350" Width="525"> <Grid> <RoutedEventsCreationSample:CustomUserControl OrderCompleted="CustomUserControl_OrderCompleted" /> </Grid> </Window>

That’s it. Hope this will help you in routed events creation process.

Advertisements