BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Binding - DataContext

The ninety-second part of the Windows Presentation Foundation Fundamentals tutorial continues to look at data binding. This instalment considers the DataContext property of WPF controls, which allows binding to any object.

Adding the Bindings

As mentioned earlier, when you are setting the data context for a control, or for its parents, you can define the bindings using only a Path value. For example, to bind the first TextBox's Text property to the FirstName property of the data object, you can use the following binding expression:

{Binding Path=FirstName}

Let's set the bindings for the two TextBoxes using this syntax. Change the first name TextBox's XAML as follows:

<TextBox Grid.Column="1" Margin="5 0 0 5" Text="{Binding Path=FirstName}"/>

For the second TextBox use:

<TextBox Grid.Column="1" Grid.Row="1" Margin="5 0 0 5" Text="{Binding Path=LastName}"/>

We can set up a similar binding for the Slider's Value property and the Text of the age TextBlock. These will both be bound to the Age property from the data object. You can bind the same data as many times as is necessary for your project.

<Slider Minimum="16" Maximum="120" Value="{Binding Path=Age}" />
<TextBlock HorizontalAlignment="Center" Text="{Binding Path=Age}"/>

Setting the Data Context

To make the demonstration complete we need to set the data context for the controls. For simplicity, we'll set the data context for the entire window. This will mean that every control within the window will have the same DataContext value.

To set the data context, modify the code behind the window. Update the constructor for the window as follows. This code sets the DataContext for the window after the controls are initialised.

public MainWindow()
{
    InitializeComponent();
    DataContext = PersonalDetails.GetDetails();
}

Run the program to see the results. When first loaded, the default personal details for Bob Smith, aged 25, are displayed. This information is retrieved from the underlying PersonalDetails object. Try moving the slider. You should see that the text version of the person's age updates too, as they are both bound to the same data context property.

Simplifying the Binding Expressions

So far we've specified the path to a bound property by explicitly setting the Path value in the binding expression. This can be useful and can add readability to complex bindings. However, for simple bindings such as the ones in our example, the "Path=" section can be excluded. To demonstrate, make the following updates:

Firstly, replace the XAML for the first TextBox with the code below:

<TextBox Grid.Column="1" Margin="5 0 0 5" Text="{Binding FirstName}"/>

For the second TextBox use:

<TextBox Grid.Column="1" Grid.Row="1" Margin="5 0 0 5" Text="{Binding LastName}"/>

Finally, remove the explicit Paths from the Slider and TextBlock that show the age.

<Slider Minimum="16" Maximum="120" Value="{Binding Age}" />
<TextBlock HorizontalAlignment="Center" Text="{Binding Age}"/>

Run the program to test it. You should find that its functionality is unchanged.

Reusing the Data Context

You can use the same object as the data context for multiple controls, or even for different windows. We can demonstrate this easily by allowing more than one window to be opened, each linking to the same singleton personal details object.

Let's try it. Start by registering the Click event for the Button control:

<Button Grid.Column="1" Grid.Row="3"
        HorizontalAlignment="Right" Click="New_Click">New Window</Button>

Now add the code for the event, as follows:

private void New_Click(object sender, RoutedEventArgs e)
{
    new MainWindow().Show();
}

Run the program and use the button to open several new windows. Each will be bound to the same PersonalDetails object, so changing the values in one window will show the new data in all of the others. The time of updating varies for different WPF controls. You will see that dragging the slider causes immediate updates, whereas altering the text in a text box does not. Only when the focus leaves the text box does the bound data change. We'll see how to change this behaviour in a later article.

31 August 2014