×
iFour Logo

Introduction to DataContext And AutoWire in WPF

iFour Team - January 18, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

Sustainable

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.

  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 Table of Content 1. What is DataContext? 2.Auto-wire with ViewModelLocator 3. Conclusion 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. 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.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

A complete guide on eCommerce conversion rate optimization
A complete guide on eCommerce conversion rate optimization

Table of Content 1. Define your goals 2. Know your target audience 3. Simplified UI/UX design, simple navigation, and high resolution images 4. Design a dedicated landing...

Read More
A comprehensive guide on the Construction management software
A comprehensive guide on the Construction management software

Table of Content 1. Mobile compatibility and inventory management 2. Accurately forecast job costs and monitor them 3. STACK 4. On-premises software is better suited...

Read More
Java And Environment Variables: A Brief Overview
Java And Environment Variables: A Brief Overview

Java is one of many programming languages that have shown much promise in the coding world. With that said, there are many components to consider, when working with Java, including...

Read More