#592 – Adding an Event Handler in Code
July 2, 2012 1 Comment
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);