#500 – Sharing an Event Handler Across Multiple Controls, Method 1

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).

        <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"

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));


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

6 Responses to #500 – Sharing an Event Handler Across Multiple Controls, Method 1

  1. André says:

    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

  2. Pingback: Dew Drop – February 23, 2012 (#1,272) | Alvin Ashcraft's Morning Dew

  3. Pingback: #500 – Sharing an Event Handler Across Multiple Controls, Method II « 2,000 Things You Should Know About WPF

  4. Mohan says:

    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

    • Sean says:

      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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: