#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)
        {
            MessageBox.Show("Click");
        }

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

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 comment