#501 – Sharing an Event Handler Across Multiple Controls, Method II

If you want to use an event handler to handle an event originating from several controls, you can specify the handler for each control and then use the RoutedEventArgs.Source property to determine the control that originated the event.

You can also just specify a handler for the Button.Click event on the parent panel that holds all of the buttons.  It will handle all Click events that originate lower down in the visual tree.

    <StackPanel ButtonBase.Click="Button_Click">
        <Button Content="Keaton" HorizontalAlignment="Center" Padding="10,5" Margin="5"/>
        <Button Content="Chaplin" HorizontalAlignment="Center" Padding="10,5" Margin="5"/>
        <Button Content="Arbuckle" HorizontalAlignment="Center" Padding="10,5" Margin="5"/>
    </StackPanel>

The event handler is the same as before–you can check the RoutedEventArgs.Source property to determine the Button that originated 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));
        }
Advertisements