Jul 15, 2015

Using the DataContext

The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from. Simply put, it allows you to specify a basis for your bindings
There's no default source for the DataContext property (it's simply null from the start), but since a DataContext is inherited down through the control hierarchy, you can set a DataContext for the Window itself and then use it throughout all of the child controls. Let's try illustrating that with a simple example: 

<Window x:Class="WpfTutorialSamples.DataBinding.DataContextSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataContextSample" Height="130" Width="280">
        <StackPanel Margin="15">
                <WrapPanel>
                        <TextBlock Text="Window title:  " />
                        <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="150" />
                </WrapPanel>
                <WrapPanel Margin="0,10,0,0">
                        <TextBlock Text="Window dimensions: " />
                        <TextBox Text="{Binding Width}" Width="50" />
                        <TextBlock Text=" x " />
                        <TextBox Text="{Binding Height}" Width="50" />
                </WrapPanel>
        </StackPanel>
</Window>
 
using System;
using System.Windows;
namespace WpfTutorialSamples.DataBinding
{
        public partial class DataContextSample : Window
        {
                public DataContextSample()
                {
                        InitializeComponent();
                        this.DataContext = this;
                }
        }
}

 
The Code-behind for this example only adds one line of interesting code: After the standard InitalizeComponent() call, we assign the "this" reference to the DataContext, which basically just tells the Window that we want itself to be the data context.
In the XAML, we use this fact to bind to several of the Window properties, including Title, Width and Height. Since the window has a DataContext, which is passed down to the child controls, we don't have to define a source on each of the bindings - we just use the values as if they were globally available.

No comments:

Post a Comment