#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"
        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.Find"
                        CanExecute="Find_CanExecute"
                        Executed="Find_Executed"/>
    </Window.CommandBindings>

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

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

1091-001

 

Advertisement

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

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

  1. Pingback: Dew Drop – June 11, 2014 (#1795) | 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 )

Connecting to %s

%d bloggers like this: