#1,090 – Sender vs. Source in CommandBinding Event Handlers

When handling a command’s Executed or CanExecute events, you can check the ExecutedRoutedEventArgs.Source or CanExecuteRoutedEventArgs.Source properties 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.

The difference is:

  • The Source property refers to the originator of the event
  • The sender parameter refers to the object that owns the event handler

In the example below, clicking on the Button initiates a Paste command, which is bound to code using the parent Window’s CommandBindings property.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Commands" Width="320" Height="220">

    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Paste"
                        CanExecute="Paste_CanExecute"
                        Executed="Paste_Executed"/>
    </Window.CommandBindings>

    <StackPanel>
        <Button Content="Paste"
                Command="ApplicationCommands.Paste"
                Margin="10" Padding="10,3"
                HorizontalAlignment="Center" />
    </StackPanel>
</Window>

The Button is the Source of the routed command and the main Window is the sender.

1090-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,090 – Sender vs. Source in CommandBinding Event Handlers

  1. Pingback: Dew Drop – June 10, 2014 (#1794) | Morning Dew

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: