This article explains the DataContext property in WPF. The DataContext property in WPF is the default binding source because it is automatically inherited by all children of the element where it is assigned.
How DataContext is used
The DataContext property sets the basis of all binding down through the hierarchy of controls .This saves you from the problem of manually defining the source of each binding, hence it saves time. Rather than defining the source multiple times for binding. It also improves object oriented code readability.
Step 1
First we create a WPF application using the following procedure:
- Open Visual Studio.
- Select the C# language and "WPF Application".
- Name the project "DataContext".
- Click on the "OK" button.

Step 2
- Now go to the MainWindow.xaml.
- Delete the Grid tag.
- Write the following code in MainWindow.xaml:
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Margin="15" Width="452" Background="#FFDED022">
<WrapPanel>
<Label Content ="Window Title: " />
<TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="200" />
</WrapPanel>
<WrapPanel Margin="0,10,0,0">
<Label Content="Window Dimensions: " />
<TextBox Text="{Binding Width}" Width="100" />
<Label Content =" x " />
<TextBox Text="{Binding Height}" Width="100" />
</WrapPanel>
</StackPanel>
</Window>
- Corresponding to the code above the window looks as:

Step 3
- Now go to the MainWindow.xaml.cs.
- Write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication14
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
}
}
Output
Press F5.

Join the conversation! Your thoughts help the community grow.