How to Add Events to Custom WPF Control
So far I've discussed about basics of creating a custom WPF control and how to add properties to it. In this post I want to write about adding events to a custom WPF control.
Adding events to custom controls is very similar to adding properties to them in the way that we register them within our control's static constructor. We use RoutedEvents to declare our events. As you may know there are three types of RoutedEvents available in WPF (Bubble, Direct and Tunnel) that you can use in your controls (find more about Events in Windows Presentation Foundation from my article on ASP Alliance).
In order to add RoutedEvents to a custom control you can declare a public static RoutedEvent in your class and use EventManager.RegisterRoutedEvent() method to register these events. EventManager.RegisterRoutedEvent() gets four parameters: the string value of event name, routing strategy (Bubble, Direct or Tunnel), type of RoutedEventHandler and type of the custom control.
Following is a simple example that demonstrates this in action by adding a new routed event named Keyvan to a custom WPF control with Bubble routing strategy.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace WPFCustomControl
{
public class MyControl : ItemsControl
{
static MyControl()
{
EventManager.RegisterRoutedEvent("Keyvan", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(MyControl));
}
public static RoutedEvent KeyvanEvent;
public event RoutedEventHandler Keyvan
{
add { AddHandler(KeyvanEvent, value); }
remove { RemoveHandler(KeyvanEvent, value); }
}
protected virtual void OnKeyvan()
{
RoutedEventArgs args = new RoutedEventArgs();
args.RoutedEvent = KeyvanEvent;
RaiseEvent(args);
}
}
}
Now playing: Modern Talking - Summer In December
[advertisement] Axosoft OnTime 2008 is four developer tools in one: bug tracking, project wiki, feature management, and help desk. It manages your development process so developers can focus on coding. Installed or Hosted – Free Single-user license -- Free 30-day team trial.
4 Comments : 05.08.07
Feedbacks
Just to let you know, there's a bug in the code you provide. Line 13:
EventManager.RegisterRoutedEvent("Keyvan",
Should be:
KeyvanEvent = EventManager.RegisterRoutedEvent("Keyvan",
With the present code you'll get an ArgumentNullException when trying to add an event handler.

#1
DotNetKicks.com
05.08.2007 @ 11:16 AM