DataGrid in WPF MVVM

DataGrid in MVVM
As we know datagrid plays a vital role in displaying data in our apllications. In this article we will get to know how to bind a datagrid in WPF MVVM.

Step 1: Lets add a DataGrid Control in Main Window as below:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>
        </Grid.RowDefinitions>
        <DataGrid x:Name="DataGridMVVM"  Grid.Column="0"  Grid.Row="1" Margin="5" IsReadOnly="True" ></DataGrid>
    </Grid>
</Window>

Step 2:
Now to Bind DataGrid to a list, we need to create a list in ViewModel:

Lets add a class named as EmployeeDetails and add some properties like Name, LastName,Qualification,Salary in that class.This class we will be using to create our ;list in MainWindowViewModel.

So here we go: Add a class under ViewModel itself:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1.ViewModel
{
    public class EmployeeDetail
    {
        public string Name
        {
            get;
            set;
        }
        public string LastName
        {
            get;
            set;
        }
        public decimal Salary
        {
            get;
            set;
        }
        public string Qualification
        {
            get;
            set;
        }
    }
}


Step 3:
Now, Moving forward to the MainWindowViewModel, we need to add a listproperty and add some items in this list.

So add the property:
public List<EmployeeDetail> employeeDetailList
{
    get { return GetValue(() => this.employeeDetailList); }
    set { SetValue(() => this.employeeDetailList, value); }
}  


Step 4:
Now we need to add some items to the list, for that we will create a method that would be doing this task for us:

 public void AddDetailsToList()
{
    employeeDetailList = new List<EmployeeDetail>();
    EmployeeDetail employeeDetail = new EmployeeDetail();
    employeeDetail.Name = "Gagan";
    employeeDetail.LastName = "Godara";
    employeeDetail.Qualification = "B.tech";
    employeeDetail.Salary = 1111;
    employeeDetailList.Add(employeeDetail);
    employeeDetail = new EmployeeDetail();
    employeeDetail.Name = "Neha";
    employeeDetail.LastName = "Jangra";
    employeeDetail.Qualification = "B.tech";
    employeeDetail.Salary = 1111;
    employeeDetailList.Add(employeeDetail);
}

So in above method we have added two records to the list.

Step 5: Now we just need to invoke this method , so I am going to do it in IntitializeCollections , you can do it anywhere you want the list to get filled to display in the datagrid.

 public override void IntitializeCollections()
{
    AddDetailsToList();
}


So Now your MainWindowViewModel Code should look like below code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1.ViewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
        /// <summary>
        /// It will thefirst thing to run when ever a ViewModel is called.
        /// </summary>
        public override void IntitializeCollections()
        {
            AddDetailsToList();
        }


        public List<EmployeeDetail> employeeDetailList
        {
            get { return GetValue(() => this.employeeDetailList); }
            set { SetValue(() => this.employeeDetailList, value); }
        }


        public void AddDetailsToList()
        {
            employeeDetailList = new List<EmployeeDetail>();
            EmployeeDetail employeeDetail = new EmployeeDetail();
            employeeDetail.Name = "Gagan";
            employeeDetail.LastName = "Godara";
            employeeDetail.Qualification = "B.tech";
            employeeDetail.Salary = 1111;
            employeeDetailList.Add(employeeDetail);
            employeeDetail = new EmployeeDetail();
            employeeDetail.Name = "Neha";
            employeeDetail.LastName = "Jangra";
            employeeDetail.Qualification = "B.tech";
            employeeDetail.Salary = 1111;
            employeeDetailList.Add(employeeDetail);
        }
    }
}

Step 6: Now, we need to bind pour DataGrid control withe above list, so lets go to MainWindow.xaml and add some lines of xaml:
add the itemsource to the DataGrid and Bind that ItemsSource to the list we created in the ViewModel.

 <DataGrid x:Name="DataGridMVVM"   Grid.Column="0"  ItemsSource="{Binding employeeDetailList ,UpdateSourceTrigger=PropertyChanged}"                  Grid.Row="1" Margin="5" IsReadOnly="True" ></DataGrid>

Step 7: Now its the turn to bind the columns of list to the datagrid to the fields in the list.
We just need to add the datagrid.columns and bind them as below:
<DataGrid x:Name="DataGridMVVM"
                  Grid.Column="0"  ItemsSource="{Binding employeeDetailList ,UpdateSourceTrigger=PropertyChanged}"
                  Grid.Row="1"
                  Margin="5" IsReadOnly="True" >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Name" Width="*" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock x:Name="lblName" Text="{Binding Path=Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Last Name" Width="*" SortMemberPath="LastName" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">

                                <TextBlock x:Name="lblTotal" Text="{Binding Path=LastName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Qualification" Width="*" SortMemberPath="Qualification" Binding="{Binding Path=Qualification,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></DataGridTextColumn>

                <DataGridTemplateColumn Header="Salary" Width="*" SortMemberPath="Salary" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="$"></TextBlock>
                                <TextBlock x:Name="lblTotal" Text="{Binding Path=Salary,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>



Thats all we need to do, now lets move forward and run the application to see the results:





Comments

Popular Posts

How to position controls using Canvas control in WPF using MVVM

Change font and size in visual studio