#500 – Sharing an Event Handler Across Multiple Controls, Method 1
February 23, 2012 6 Comments
You can use the same event handler for more than one control by specifying the handler for each control and pointing to the same event handler code.
In the example below, we have three buttons, each of which wires up a handler for the Click event, but using the same handler (Button_Click).
<StackPanel> <Button Content="Keaton" HorizontalAlignment="Center" Padding="10,5" Margin="5" Click="Button_Click"/> <Button Content="Chaplin" HorizontalAlignment="Center" Padding="10,5" Margin="5" Click="Button_Click"/> <Button Content="Arbuckle" HorizontalAlignment="Center" Padding="10,5" Margin="5" Click="Button_Click"/> </StackPanel>
In the Button_Click event handler, we can check the Source property of the RoutedEventArgs parameter to determine which button sent us the event.
private void Button_Click(object sender, RoutedEventArgs e) { // Get at originator of event using RoutedEventArgs.Source property Button b = e.Source as Button; MessageBox.Show(string.Format("You clicked on {0} button", b.Content)); }
Hi,another way to do the same would be to handle the routed event ButtonBase.Click on the StackPanel (or another ancestor in the visual tree). Cheers
Patience. :O)
Pingback: Dew Drop – February 23, 2012 (#1,272) | Alvin Ashcraft's Morning Dew
Pingback: #500 – Sharing an Event Handler Across Multiple Controls, Method II « 2,000 Things You Should Know About WPF
I would like to know how can I handle it events raised from multiple controls across multiple files at a central location like App.xaml.cs
Mohan, you could either have a handler on the window that owns the control invoke a method in App.xaml.cs or you could wire up the handlers in your code, from App.xaml.cs. Depending on what you’re doing, however, data binding is a better solution than wiring up handlers.