#593 – AddHandler Method Can Add Handler for Any Event

If you’re adding an event handler from code, rather than specifying the handler in XAML, you can just use the += notation for an event that is defined for the control in question.  For example, the Button control defines a Click control, so you can do the following:

myButton.Click += new RoutedEventHandler(Button_Click);

But let’s say that you want to add a handler for the Click event to a StackPanel control, which does not define the Click event, and you want to do it from code.  You can then use the AddHandler syntax:

myStackPanel.AddHandler(ButtonBase.ClickEvent, (RoutedEventHandler)HandleTheClick);

Notice that the AddHandler method accepts any routed event type as its first parameter.  This means that any UIElement instance can call its AddHandler method to indicate that it wants to handle any routed event.  Even though StackPanel doesn’t define a Click event, it can handle the Button’s Click event.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #593 – AddHandler Method Can Add Handler for Any Event

  1. Pingback: Dew Drop – July 3, 2012 (#1,356) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: