#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()));
        }