wpf Defining the DataContext


Example

In order to work with bindings in WPF, you need to define a DataContext. The DataContext tells bindings where to get their data from by default.

<Window x:Class="StackOverflowDataBindingExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StackOverflowDataBindingExample"
        xmlns:vm="clr-namespace:StackOverflowDataBindingExample.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:HelloWorldViewModel />
    </Window.DataContext>
    ...
</Window>

You can also set the DataContext through code-behind, but it is worth noting that XAML IntelliSense is somewhat picky: a strongly-typed DataContext must be set in XAML for IntelliSense to suggest properties available for binding.

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new HelloWorldViewModel();
    }
}

While there are frameworks to help you define your DataContext in a more flexible way (e.g. MVVM Light has a viewmodel locator that uses inversion of control), we use the quick and dirty method for the purposes of this tutorial.

You can define a DataContext for pretty much any visual element in WPF. The DataContext is generally inherited from ancestors in the visual tree unless it has been explicitly overridden, e.g. inside a ContentPresenter.