#1,091 – Using a CommandTarget to Change the Source of a Routed Command

The source of a routed command is the element that is invoking the command.  The sender parameter in the Executed or CanExecute handlers is the object that owns the event handler.  Setting the Command parameter of a Button to a particular command and then binding the command to some code in the CommandBindings for a main Window, the button is the source and the window is the sender.

When setting the Command property, you can also set the CommandTarget property, indicating a different element that should be treated as the source of the routed command.

<Window x:Class="WpfApplication1.MainWindow"
        Title="Commands" Width="320" Height="220">

        <CommandBinding Command="ApplicationCommands.Find"

        <TextBox Name="txtSomeText"
                 Width="140" Height="25" Margin="10"/>
        <Button Content="Find"
                CommandTarget="{Binding ElementName=txtSomeText}"
                Margin="10" Padding="10,3"
                HorizontalAlignment="Center" />

The Find command now appears to originate from the TextBox.  We can see this in the event handler for the Executed event.