#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 software development and sailing.

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 comment