C# & VB .NET • Route Events in WPF

Listing 1. Routed events in WPF require special syntax that includes declaring whether the event will move up (bubble) or down (tunnel) through the container hierarchy. For example, you can crate an event that fires when a text box contains a specific value and use this to spawn an animation. Note that Workflow defines events somewhat differently.

//C#
public class SpecialTextBox : TextBox

{
	protected override void OnTextChanged(
		TextChangedEventArgs e)
	{
		base.OnTextChanged(e);
		if (this.Text == "Fred")
		{
			RoutedEventArgs args = new 
				RoutedEventArgs(ChangedToFredEvent);
			base.RaiseEvent(args);
		}
	}

	public static readonly RoutedEvent ChangedToFredEvent = 
		EventManager.RegisterRoutedEvent("ChangedToFred", 
		RoutingStrategy.Bubble, typeof(RoutedEventHandler), 
		typeof(CustomerWindow));

	public event RoutedEventHandler ChangedToFred
	{
		add { AddHandler(SpecialTextBox.ChangedToFredEvent, 
			value); }
		remove { RemoveHandler(
			SpecialTextBox.ChangedToFredEvent, value); }
	}
}

'VB .NET Version
Public Class SpecialTextBox
	Inherits TextBox

	Protected Overrides Sub OnTextChanged( _
		ByVal e As TextChangedEventArgs)
		MyBase.OnTextChanged(e)
		If Me.Text = "Fred" Then
			Dim args As New RoutedEventArgs( _
				ChangedToFredEvent)
			MyBase.RaiseEvent(args)
		End If
	End Sub

	Public Shared ReadOnly ChangedToFredEvent _
		As RoutedEvent = EventManager.RegisterRoutedEvent( _
		"ChangedToFred", RoutingStrategy.Bubble, _
		GetType(RoutedEventHandler), GetType(Window1))

	Custom Event ChangedToFred As RoutedEventHandler
		AddHandler(ByVal value As RoutedEventHandler)
			MyBase.AddHandler(ChangedToFredEvent, value)
		End AddHandler
		RemoveHandler(ByVal value As RoutedEventHandler)
			MyBase.RemoveHandler(ChangedToFredEvent, value)
		End RemoveHandler
		RaiseEvent(ByVal sender As Object, ByVal e As _
			System.Windows.RoutedEventArgs)
			MyBase.RaiseEvent(e)
		End RaiseEvent
	End Event

	Public Sub OnChangedToFred()
		Dim e As New RoutedEventArgs(ChangedToFredEvent)
		RaiseEvent ChangedToFred(Me, e)
	End Sub
End Class