#106 – Set Property Value to Point to Another Object

There are times when you’d like to set a property value on one element to point to an instance of another element and do this in XAML, rather than in code.

An example of this is the CommandTarget property, which is used to indicate the control that should be the target of the command being initiated from a control.

For example, if you have a Button that executes a Paste command and you want the contents pasted in a TextBox, you’d set the button’s CommandTarget property to point to the TextBox.

This is done in XAML using the Binding markup extension, setting its ElementName property to point to the desired control.

 <Button Content="Paste" Command="ApplicationCommands.Paste"
     CommandTarget="{Binding ElementName=myTextBox}" />
 <TextBox Name="myTextBox"/>

XAML 2009 allows using the x:Reference markup extension, but this is not supported in compiled XAML in WPF.

 <Button Content="Paste" Command="ApplicationCommands.Paste"
     CommandTarget="{x:Reference myTextBox}" />
 <TextBox Name="myTextBox"/>
Follow

Get every new post delivered to your Inbox.

Join 356 other followers