#502 – Sender vs. RoutedEventArgs.Source

When handling a routed event, you can check the RoutedEventArgs.Source property to get at the control that is the originator of the event.  But the event handler also includes a sender parameter that in many cases also points to the originator of the event.

In the case of routed events, RoutedEventArgs.Source will refer to the originator of the event and sender will refer to the object that owns the event handler.

In the example below, RoutedEventArgs.Source will refer to the Button that a user clicked on, while sender will refer to the StackPanel to which the  Click event is attached.

    <StackPanel ButtonBase.Click="Button_Click">
        <Button Content="Keaton" />
        <Button Content="Chaplin" />
        <Button Content="Arbuckle" />
    </StackPanel>

 

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button b = e.Source as Button;
            MessageBox.Show(string.Format("You clicked on {0} button, sender is of type {1}",
                b.Content, sender.GetType().ToString()));
        }

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

One Response to #502 – Sender vs. RoutedEventArgs.Source

  1. Pingback: Dew Drop – February 27, 2012 (#1,275) | Alvin Ashcraft's Morning Dew

Leave a comment