DataContext is the most basic concept of Data Binding in WPF. It is like providing data source in the binding. It allows elements to inherit data source from its parent.
In a very layman language, DataContext is used to provide communication between ViewModel and View.
If the DataContext property of a parent is provided, it is inherited by all its children. In the actual scene child lookup for the data source and pick the value from nearest source.
Namespace: System.Windows
Assembly: PresentationFramework (in PresentationFramework.dll)
We can define DataContext in 3 ways. Let us look them one by one.
1. Define it in Window.DataContext
By defining it in Window level all the child elements can use it.
XAML File
<vm:ViewModel></vm:ViewModel>
</Window.DataContext>
2. Define it as Window.Resource
XAML File
<vm:ViewModel x:Key=”LoginViewModelkey”/ >
</Window.Resources>
<WrapPanel Margin=”20,30″ DataContext=”{StaticResource LoginViewModelkey }” >
</WrapPanel >
3. Define it in Code-behind
Code Behind – .CS File
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
Let us take an example where we are creating a ViewModel which contains data for our view. Now you can set DataContext for the MainWindow by any of the above 3 discussed ways. I am taking first way to define DataContext (i.e, Window.Context) as i like this way the most.
XAML File
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:vm=”clr-namespace:DataContextWpf”
Title=”MainWindow” Height=”350″ Width=”525″ Background=”#98dafc” >
<Window.DataContext>
<vm:ViewModel></vm:ViewModel>
</Window.DataContext>
<WrapPanel Margin=”20,30″>
<TextBlock Text=”EmpId :” />
<TextBox Width=”200″ Height=”30″ Text=”{Binding EmpId}” Background=”Orange” />
<TextBlock Text=”Name :” />
<TextBox Width=”200″ Height=”30″ Text=”{Binding Name}” Background=”Orange” />
</WrapPanel>
</Window>
ViewModel Class – .CS File
{
public class ViewModel
{
private string empId;
public string EmpId
{
get { return empId; }
set { empId = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public ViewModel()
{
EmpId = “Ms101”;
Name = “Bill Gates”;
}
}
}
Output