#592 – Adding an Event Handler in Code

You typically specify handlers for routed events in XAML:

        <Button Content="Like" Click="Button_Click"/>

You then add the code for the handler in your code-behind:

        private void Button_Click(object sender, RoutedEventArgs e)

You can also add the handler from code. Adding a handler to the Button control for the  Click event requires that you give the Button control a name that you can then reference from your code-behind.

        <Button Name="myButton" Content="Like"/>

You can then add a handler by using the += operator on the event for which you want a handler.

myButton.Click += new RoutedEventHandler(Button_Click);

This is equivalent to calling the UIElement.AddHandler method.

            myButton.AddHandler(ButtonBase.ClickEvent, (RoutedEventHandler)Button_Click);

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 #592 – Adding an Event Handler in Code

  1. Pingback: Dew Drop – July 2, 2012 (#1,355) | 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: