Appendix J. Data Binding

This appendix briefly summarizes useful data-binding techniques. You can use it to refresh your memory about specific data-binding scenarios. For more information on data binding, see Chapter 18.

Binding Components

Data bindings have these four basic pieces:

  • Target — The object that will use the result of the binding

  • Target Property — The target object's property that will use the result

  • Source — The object that provides a value for the target object to use

  • Path — A path that locates the value within the source object

Binding to Elements by Name

The following code binds a Label to a TextBox so it displays whatever you type in the TextBox. This version places a separate Binding object inside the TextBlock to define its contents.

<TextBox Name="txtTypeHere" Margin="5" Height="30"
 VerticalAlignment="Top" Text="Type here!"/>

<Label Margin="5" BorderBrush="Yellow" BorderThickness="1">
    <Binding ElementName="txtTypeHere" Path="Text"/>
</Label>

The following code makes a similar binding but using an attribute:

<TextBox Name="txtTypeHere" Margin="5" Height="30"
 VerticalAlignment="Top" Text="Type here!"/>

<Label Margin="5" BorderBrush="Yellow" BorderThickness="1"
 Content="{Binding ElementName=txtTypeHere, Path=Text}"/>

Binding to RelativeSource

The binding's RelativeSource property lets you specify a source object via its relationship to the target control. Sometimes this is useful for binding two properties to each other for the same control.

For example, the following code binds ...

Get WPF Programmer's Reference: Windows Presentation Foundation with C# 2010 and .NET 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.