×

iFour Logo

Introduction to DataContext And AutoWire in WPF

Kapil Panchal - January 18, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
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
  1. Using XAML side
  2. 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.

Simpleaction

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























			  
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:
Simpleaction

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.


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.

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

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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...