#1,090 – Sender vs. Source in CommandBinding Event Handlers
June 10, 2014 2 Comments
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.