DataContext is one of the most useful concepts of Data Binding. DataContext is a property that is defined within FrameWorkElement. This is the default source of your bindings. For binding an object, we need some data from somewhere. There are a few ways to specify the source of data. We can use the Source property for binding, inherit a DataContext, and ElementName and RelativeSource properties are also used for binding an object. Data Binding means when we change the property of one control then another match will automatically be updated.
DataContext with data binding can provide a hierarchical data presentation. It connects the front end to the code-behind and enables changes to the data. The default DataContext property is simply null from the start, we can set DataContext for Window and use it all of the child controls.
There are two ways to use DataContext in our project.
id
Using XAML side
Code-behind
Let’s see the example one by one. First, we can create an example using code-behind.
Step: 1
First of all, start the Visual Studio and select the WPF project.
After selecting the WPF App (.NET Framework), Give it the appropriate name and click to create a button.
Step: 2
After creating a project just open MainWindow.Xaml file and add the below code or you can create a design that you want to show.
In the code-behind example, after the InitalizeComponent() we need only one line of code just assign DataContext with “this” reference. This can tell the Window that we want to be the DataContext.
Now, we can create an example of DataContext using XAML code.
Step: 1
First, create a WPF project and open it.
Step: 2
First, create a View Model name it MainViewModel and add the get set method.
First of all, we can add DataContext for binding purposes. Here we can bind a MainViewModel that can inherit Employee class and after that using the Grid we can add two labels to show the name and the id and two TextBox for display bindable name and id.
Auto-wire with ViewModelLocator
The auto-wire is used to hookup the code between View and ViewModel. This can provide a loosely coupled way to bind the View and the ViewModel. When we use this approach, we only need to create a simple view not much more hard code the ViewModel can hook up with the View.
Conclusion
Data context can define a data source and the binding associates what specific data is shown and how. Using the data binding you can save your time and no need for long coding. In WPF some controls have their DataContext property that’s why you cannot use the same DataContext property for all controls within a Window. You can also use inheritance and override within the DataContext and you can break the chain of inheritance and override the DataContext with a new value.
Introduction to DataContext And AutoWire in WPF
What is DataContext?
DataContext is one of the most useful concepts of Data Binding. DataContext is a property that is defined within FrameWorkElement. This is the default source of your bindings. For binding an object, we need some data from somewhere. There are a few ways to specify the source of data. We can use the Source property for binding, inherit a DataContext, and ElementName and RelativeSource properties are also used for binding an object. Data Binding means when we change the property of one control then another match will automatically be updated.
DataContext with data binding can provide a hierarchical data presentation. It connects the front end to the code-behind and enables changes to the data. The default DataContext property is simply null from the start, we can set DataContext for Window and use it all of the child controls.
There are two ways to use DataContext in our project.
id
Using XAML side
Code-behind
Let’s see the example one by one. First, we can create an example using code-behind.
Step: 1
First of all, start the Visual Studio and select the WPF project.
After selecting the WPF App (.NET Framework), Give it the appropriate name and click to create a button.
Step: 2
After creating a project just open MainWindow.Xaml file and add the below code or you can create a design that you want to show.
MainWindow.Xaml
Read More: What Are The Different Ways Of Binding In Wpf?
Step: 3
MainWindow.Xaml.cs
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Data;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Imaging;
usingSystem.Windows.Navigation;
usingSystem.Windows.Shapes;
namespaceDataContext
{
publicpartialclassMainWindow : Window
{
publicMainWindow()
{
InitializeComponent();
Employee P = newEmployee("Hello World");
P.State = "MD";
AnotherClass c = newAnotherClass();
c.EmployeeNameTest = P;
c.AnotherField = "Another Value";
this.DataContext = c;
}
}
publicclassAnotherClass :INotifyPropertyChanged
{
privatestringanotherfield;
private Employee emp;
publicstringAnotherField
{
get{ returnanotherfield; }
set
{
anotherfield = value;
OnPropertyChanged("AnotherField");
}
}
public Employee EmployeeNameTest
{
get{ return emp; }
set
{
emp = value;
OnPropertyChanged("EmployeeNameTest");
}
}
publiceventPropertyChangedEventHandlerPropertyChanged;
protectedvoidOnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, newPropertyChangedEventArgs(name));
}
}
publicoverridestringToString()
{
returnstring.Format("My ToString implementation of AnotherClass");
}
}
publicclassEmployee :INotifyPropertyChanged
{
privatestringnameofemployee;
privatestringstateofemployee;
// Declare the event
publiceventPropertyChangedEventHandlerPropertyChanged;
publicEmployee()
{
}
publicEmployee(string value)
{
this.nameofemployee = value;
}
publicstringEmployeeName
{
get{ returnnameofemployee; }
set
{
nameofemployee = value;
OnPropertyChanged("EmployeeName");
}
}
publicstring State
{
get{ returnstateofemployee; }
set
{
stateofemployee = value;
OnPropertyChanged("State");
}
}
protectedvoidOnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, newPropertyChangedEventArgs(name));
}
}
}
}
Output:
In the code-behind example, after the InitalizeComponent() we need only one line of code just assign DataContext with “this” reference. This can tell the Window that we want to be the DataContext.
Now, we can create an example of DataContext using XAML code.
Step: 1
First, create a WPF project and open it.
Step: 2
First, create a View Model name it MainViewModel and add the get set method.
MainViewModel.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceDataContext
{
publicclassMainViewModel
{
publicNameofEmployeeMyEmployee{ get; set; }
}
}
Wants to Talk with Our Highly Skilled WPF Developer? Contact Now.
See here
Step: 3
After that, create an Employee Class to display the employee’s name and id.
Employee.cs
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceDataContext
{
publicclassNameofEmployee
{
publicNameofEmployee()
{
EmployeeDetailsemployeeDetails = newEmployeeDetails();
employeeDetails.EmpID = 123;
employeeDetails.EmpName = "ABC";
}
}
publicclassEmployeeDetails
{
privateintempID;
publicintEmpID
{
get
{
returnempID;
}
set
{
empID = value;
}
}
privatestringempName;
publicstringEmpName
{
get
{
returnempName;
}
set
{
empName = value;
}
}
}
}
Step: 4
MainWindow.Xaml
First of all, we can add DataContext for binding purposes. Here we can bind a MainViewModel that can inherit Employee class and after that using the Grid we can add two labels to show the name and the id and two TextBox for display bindable name and id.
Auto-wire with ViewModelLocator
The auto-wire is used to hookup the code between View and ViewModel. This can provide a loosely coupled way to bind the View and the ViewModel. When we use this approach, we only need to create a simple view not much more hard code the ViewModel can hook up with the View.
Conclusion
Data context can define a data source and the binding associates what specific data is shown and how. Using the data binding you can save your time and no need for long coding. In WPF some controls have their DataContext property that’s why you cannot use the same DataContext property for all controls within a Window. You can also use inheritance and override within the DataContext and you can break the chain of inheritance and override the DataContext with a new value.
Kapil Panchal
A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.
Introduction
Imagine standing in line at the grocery store, waiting to pay for groceries. You pull out your phone and scan each item’s barcode with a single tap. This seemingly...
Before navigating into the world of DevOps, it's important to know what DevOps is exactly. DevOps is a methodology that uses continuous integration, continuous delivery, and automation to shorten the software delivery lifecycle (SDLC). More than just a set of practices, DevOps embodies a culture and a philosophy that bridges the gap between developers (Dev) and IT operations (Ops) teams.
Microsoft PowerApps has become the preferred digital solution, particularly for non-tech clients. It is a simple and easy-to-use app development platform that does not require much coding and can help you create personalized apps effortlessly with drag-and-drop capabilities.