O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Data Binding

Data binding lets you connect properties of any .NET object to properties of user interface elements. The syntax looks pretty similar to template binding. Example 20-25 shows a simple form with a couple of text entry fields, both using data binding to hook up to a source object.

Example 20-25. Data entry with data binding

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBlock VerticalAlignment="Center" Text="Name:" />
    <TextBox Grid.Column="1"
             Text="{Binding Path=Name}" />

    <TextBlock VerticalAlignment="Center" Grid.Row="1" Text="Age:" />
    <TextBox Grid.Column="1" Grid.Row="1"
             Text="{Binding Path=Age}" />
</Grid>

Just as template bindings refer to properties on the target control, so these data binding expressions refer to properties on some source object. Data sources don’t need to be anything special—Example 20-26 shows an extremely simple class that will work just fine as the data source for Example 20-25.

Example 20-26. A very simple data source

public class Person
{
    public string Name { get; set; }
    public double Age { get; set; }
}

The code behind can create an instance of this type, and then make it available to the binding expressions in our user interface by putting it in the DataContext property as Example 20-27 shows.

Example 20-27. Setting up a data source

public partial class MainPage : UserControl ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required