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)); }
Filed under: Events Tagged: Event Handler, Events, RoutedEventArgs, WPF
