Introduction to Data Context And Auto Wire in WPF - iFour Technolab

ifourtechnolab

Harshal Suthar

Posted on May 25, 2022

Introduction to Data Context And Auto Wire in WPF - iFour Technolab

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.

Image description

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


<window height="450" mc:ignorable="d" title="MainWindow" width="800" x:class="DataContext.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:src="clr-namespace:DataContext" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<grid datacontext="{Binding Path=EmployeeNameTest}">
<grid.resources>
<src:employee employeename="Kishore1021" x:key="myDataSource">
</src:employee></grid.resources>
<grid.rowdefinitions>
<rowdefinition height="*"></rowdefinition>
<rowdefinition height="*"></rowdefinition>
<rowdefinition height="*"></rowdefinition>
<rowdefinition height="*"></rowdefinition>
<rowdefinition height="*"></rowdefinition>
<rowdefinition height="*"></rowdefinition>
</grid.rowdefinitions>
<textbox grid.row="0" name="TextBox1" text="{Binding Source={StaticResource myDataSource}, Path=EmployeeName, UpdateSourceTrigger=PropertyChanged}">
<textbox grid.row="1" name="TextBox2" text="{Binding Source= {StaticResource myDataSource}, Path=EmployeeName}"></textbox>
<textbox grid.row="2" name="TextBox3" text="{Binding Path=EmployeeName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></textbox>
<textbox grid.row="3" name="TextBox4" text="{Binding Path=EmployeeName}"></textbox>
<textblock grid.row="4" name="TextBlock1" text="{Binding Path=EmployeeName}">
<textblock grid.row="5" name="TextBlock2" text="{Binding Path=AnotherField}">
</textblock></textblock></textbox></grid>
</window>

Enter fullscreen mode Exit fullscreen mode

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));
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

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; }
    }
}

Enter fullscreen mode Exit fullscreen mode

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;
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step: 4
MainWindow.Xaml


<window height="450" mc:ignorable="d" title="MainWindow" width="800" x:class="DataContext.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:DataContext" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <window.datacontext>
        <local:mainviewmodel>
    </local:mainviewmodel></window.datacontext>
    <grid>
        <grid.rowdefinitions>
            <rowdefinition height="Auto">
            <rowdefinition height="Auto">
        </rowdefinition></rowdefinition></grid.rowdefinitions>
        <grid.columndefinitions>
            <columndefinition width="Auto">
            <columndefinition width="200">
        </columndefinition></columndefinition></grid.columndefinitions>
        <label content="ID:" grid.column="0" grid.row="0">
        <label content="Name:" grid.column="0" grid.row="1">
        <textbox grid.column="1" grid.row="0" margin="3" text="{Binding MyEmployee.EmpId}">
        <textbox grid.column="1" grid.row="1" margin="3" text="{Binding MyEmployee.EmpName}">
    </textbox></textbox></label></label></grid>
</window>

Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
ifourtechnolab
Harshal Suthar

Posted on May 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related