#1,092 – An Example of Using a CommandTarget

Setting the CommandTarget property allows an element executing a routed command to initiate the routing of a command with a different element.

In the example below, clicking on the Button initiates a Paste command, but the routed command originates with a TextBox rather than the button.  In this particular case, because a TextBox implicitly has a command binding for the Paste command, text currently in the paste buffer is automatically pasted into the TextBox.  No code-behind is required in order for this to work.

<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">

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

1092-001

Advertisements

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

One Response to #1,092 – An Example of Using a CommandTarget

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

Google+ photo

You are commenting using your Google+ 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: