XAML Data Binding DataContext


The wpf-tutorial.com website has an introductory discussion on the DataContext property. The DataContext property is the default source of your bindings, unless you specifically declare another source, as we did in the previous example 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.

Here below is the code for a project called XAMLKDataContext. When running, you can actually change the Title if you type in the text box. The program window height and width change as you resize the program. If you type in the height or width text boxes you can resize the program window. If you type a low number, such a 3, in the height box, the program automatically resizes to the minimum height. It works for width also.

<Window x:Class="XAMLDataContext.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowStartupLocation="CenterScreen"
        Title="XAMLDataContext" Height="130" Width="300" MinHeight="130" MinWidth="300">
    <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.Windows;
namespace XAMLDataContext
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }
    }
}