How to bind data in Xamgrid using WPF and MVVM


Shikha Gupta
SharePoint Developer
Published On :   06 Apr 2017
Visit Count
Today :  3    Total :   612
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!


Let’s first create a WPF application and we will be using MVVM to bind the data to xamgrid and here we will not be using any class to store our data we will read our data directly from our xml file. We will be using two xml files one will have all the column names and the other will have data corresponding to those columns.

Please follow the following steps:

1. Open visual studio and create a WPF application and give a name like “ XamgridWPFProject”.

clip_image002

Now you will see that MainWindow.Xaml and MainWindow.Xaml.cs files are created. We will be using MainWindow.Xaml for our designing purpose and for data binding we will be using MVVM.

2. Add first Xml file name Columns.xml which will contain the name of the columns

clip_image004

Copy and paste the following data in the columns xml file:

 <?xml version="1.0" encoding="utf-8"?>
 <ColumnTemplate>
   <Root>
     <NodeName>OperatingComps</NodeName>
     <NameSpace>xmlns:ns0</NameSpace>
   </Root>
   <Details Name="CompID" DataType="Text" PopupVisible="True"></Details>
   <Details Name="AddressLine1" DataType="Text" PopupVisible="True"></Details>
   <Details Name="City" DataType="Text" PopupVisible="True"></Details>
   <Details Name="Condition" DataType="Text"></Details>
   <Details Name="County" DataType="Text"></Details>
   <Details Name="SaleDate" DataType="Text" PopupVisible="True"></Details>
   <Details Name="EGIMultiplier" DataType="Text"></Details>
   <Details Name="ExpenseRatio" DataType="Text"></Details>
   <Details Name="BuyerName" DataType="Text"></Details>
   <Details Name="GrossBuildingArea" DataType="Text"></Details>
   <Details Name="YearRenovated" DataType="Text"></Details>
   <Details Name="PropertyMSA" DataType="Text" PopupVisible="True"></Details>
   <Details Name="Size" DataType="Text" PopupVisible="True"></Details>
 </ColumnTemplate>
 
 

3. Add the second xml file name Data.xml which will contain all the data for the columns.

clip_image006

Copy and paste the following data in the Data xml file:

 <?xml version="1.0" encoding="utf-8"?>
 <OperatingComps>
   <Property>
     <CompID>218017</CompID>
     <AddressLine1>6788 Route 31 East</AddressLine1>
     <City>Newark</City>
     <Condition>Good</Condition>
     <County>Wayne</County>
     <SaleDate>01/01/2106</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>175,539</GrossBuildingArea>
     <YearRenovated>2009</YearRenovated>
     <PropertyMSA>Rochester</PropertyMSA>
     <Size>175,539</Size>
   </Property>
   <Property>
     <CompID>131377</CompID>
     <AddressLine1>5000 Buford Highway</AddressLine1>
     <City>Atlanta</City>
     <Condition>Average</Condition>
     <County>Dekalb</County>
     <SaleDate>01/01/2103</SaleDate>
     <EGIMultiplier>51.2</EGIMultiplier>
     <ExpenseRatio>1,100.00</ExpenseRatio>
     <BuyerName>JV Development Group</BuyerName>
     <SellerName>Patron Partners LLC</SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated>2010</YearRenovated>
     <PropertyMSA>Atlanta</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>227491</CompID>
     <AddressLine1>30th Street</AddressLine1>
     <City>Grand Island</City>
     <Condition>Average</Condition>
     <County>Arthur</County>
     <SaleDate>10/10/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>227445</CompID>
     <AddressLine1>14th Street</AddressLine1>
     <City>Grand Island</City>
     <Condition></Condition>
     <County>Arthur</County>
     <SaleDate>10/10/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>227444</CompID>
     <AddressLine1>14th Street</AddressLine1>
     <City>Grand Island</City>
     <Condition></Condition>
     <County>Arthur</County>
     <SaleDate>10/10/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>228919</CompID>
     <AddressLine1>6556 Aaron Aronov Drive</AddressLine1>
     <City>Fairfield</City>
     <Condition>Average</Condition>
     <County>Jefferson</County>
     <SaleDate>07/06/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>8,075</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
 </OperatingComps>
 

4. Add a folder called View Model and inside that add a class name XamgridViewModel.cs

clip_image008

5. We have to add a MVVMFoundation.WPF reference for that open manage nuget packages as shown below :

i. Click on Manage Nuget Package for solutionand in the search window search for mvvmfoundation.

clip_image010

ii. Install the MVVM foundation

clip_image012

6. Add the System.Windows.Forms refernceclip_image014

7. We will be using few Infragistic references in our project to add xamgrid and if you don’t have Infragistic installed then you can use the trial version for implementing this. Now add the following references in your project.

clip_image016

clip_image018

8. Now go to MainWindow.Xaml and let’s do the designing part. Here we are going to add the button and on click of that a popup will open which will contain a grid where we will bind the data.

Inside MainWindow.Xaml copy and paste the following code.

 <UserControl x:Class="XamgridWPFProject.MainWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:ig="http://schemas.infragistics.com/xaml"
         xmlns:viewModel="clr-namespace:XamgridWPFProject.ViewModel">
     <UserControl.DataContext>
         <viewModel:XamgridViewModel/>
     </UserControl.DataContext>
     <Grid>
         <Button HorizontalAlignment="Center" Content="Get Data" Height="200" Command="{Binding BindDataCommand}"/>
         <Popup PopupAnimation="Fade" x:Name="SaleGroupCompsPopup" Height=" 250"	IsOpen="{Binding IsPreviewMode, Mode=TwoWay}" HorizontalAlignment="Center" VerticalAlignment="Center" Placement="Center" >
             <Border BorderBrush="Green" BorderThickness="1" Padding="0" HorizontalAlignment="Left" Background="White">
                 <Grid  Margin="0,0,0,0" Width="Auto">
                     <ScrollViewer>
                         <StackPanel Orientation="Vertical" Name="MainPnl">
                             <Grid Margin="8,0,5,0" Width="Auto">
                                 <Grid.RowDefinitions>
                                     <RowDefinition Height="40" />
                                     <RowDefinition Height="*"/>
                                     <RowDefinition Height="3"/>
                                 </Grid.RowDefinitions>
                                 <Button Content="Hide Popup" x:Name="HidePopup" ommand="{Binding HidePopupCommand}" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="8"/>
                                 <ig:XamGrid x:Name="GroupCompsGrid" HorizontalAlignment="Left"  Height="200" Width="1000" Grid.Row="1"  ColumnWidth="200" VerticalAlignment="Stretch" ItemsSource="{Binding Path=DataEditorDataTable, Mode=TwoWay}"  Margin="0,0,10,0" ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible">
                                     <ig:XamGrid.RowSelectorSettings>
                                         <ig:RowSelectorSettings Visibility="Visible" EnableRowNumbering="True">
                                         </ig:RowSelectorSettings>
                                     </ig:XamGrid.RowSelectorSettings>
                                     <ig:XamGrid.DataManagerProvider>
                                         <ig:AnnotationsDataManagerProvider/>
                                     </ig:XamGrid.DataManagerProvider>
                                 </ig:XamGrid>
                             </Grid>
                         </StackPanel>
                     </ScrollViewer>
                 </Grid>
             </Border>
         </Popup>
     </Grid>
 </UserControl>
 
 

Explanation: This line have been added to attach the view model with Xaml xmlns:viewModel="clr-namespace:XamgridWPFProject.ViewModel" and the following line has been added to mentioned for which ViewModel are we creating this view or xaml file <UserControl.DataContext> <viewModel:XamgridViewModel/> /UserControl.DataContext>

In the Xaml we can only bind properties or relay command. Hence for button we are binding BindDataCommand which is a relay command and which in turns call the method where we binding our data. For Popup we are using IsPreviewMode command to determine when will it visible and when it will be not.For Xamgrid we are directly binding DataEditorTable.

9. Now go to XamgridViewModel.cs and copy and paste the following code.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Collections.ObjectModel;
 using MvvmFoundation.Wpf;
 using System.Windows.Input;
 using System.Xml.Serialization;
 using System.IO;
 using System.Runtime.InteropServices;
 using System.Xml;
 using System.Threading;
 using System.Windows.Forms;
 using System.Configuration;
 using System.Data;
 using System.Windows.Data;
 using Infragistics.Controls.Grids;
 using System.Windows;
 
 namespace XamgridWPFProject.ViewModel
 {
     class XamgridViewModel : ObservableObject
     {
         private string columnConfigInputXML = string.Empty;
         XmlDocument dataXMLDoc = null;
         XmlDocument columnXMLDoc = null;
         private DataSet dsDataXML = null;
         DataTable dtDataXML = null;
         XmlNodeList columnXnList = null;
         private List<string> popupDisplayName;
 
         protected RelayCommand _bindCommand;
         public ICommand BindDataCommand
         {
             get
             {
                 if (_bindCommand == null)
                 {
                     _bindCommand = new RelayCommand(() => this.Binddata(),
                         () => this.CanBinddata());
                 }
                 return _bindCommand;
             }
         }
         
         private bool CanBinddata()
         {
             return true;
         }
         protected RelayCommand _hidePopupCommand;
         public ICommand HidePopupCommand
         {
             get
             {
                 if (_hidePopupCommand == null)
                 {
                     _hidePopupCommand = new RelayCommand(() => this.HidePopup(),
                         () => true);
                 }
                 return _hidePopupCommand;
             }
         }
         private DataTable _dataEditorDataTable;
         public DataTable DataEditorDataTable
         {
             get
             {
                 return _dataEditorDataTable;
             }
             set
             {
                 _dataEditorDataTable = value;
                 RaisePropertyChanged("DataEditorDataTable");
             }
         }
         private bool _isPreviewMode;
         public bool IsPreviewMode
         {
             get { return _isPreviewMode; }
             set
             {
                 _isPreviewMode = value;
                 RaisePropertyChanged("IsPreviewMode");
             }
         }
         public void Binddata()
         {
             // initialization
             XmlNodeReader xmlReader = null;
             dataXMLDoc = new XmlDocument();
             columnXMLDoc = new XmlDocument();
             dtDataXML = new DataTable();
             dataXMLDoc.Load(@"Data.xml");
             columnXMLDoc.Load(@"Columns.xml");
             popupDisplayName = new List<string>();
 
             // collects the column name who has @PopupVisible='True' attribute
             columnConfigInputXML = "//ColumnTemplate/Details [@PopupVisible='True']";
             columnXnList = columnXMLDoc.SelectNodes(columnConfigInputXML);
             if (columnXnList != null && columnXnList.Count > 0)
             {
                 foreach (XmlNode docVarpopupXn in columnXnList)
                 {
                     popupDisplayName.Add(docVarpopupXn.Attributes["Name"].Value);
                 }
 
             }
             //converts the xml data to datatable and bind only the selected columns and not all the columns
             xmlReader = new XmlNodeReader(dataXMLDoc);
             dsDataXML = new DataSet();
             dsDataXML.ReadXml(xmlReader);
             dtDataXML = dsDataXML.Tables[0];
             string[] selectedColumns = popupDisplayName.ToArray();
             var table = new DataView(dtDataXML).ToTable(false, selectedColumns);
             DataEditorDataTable = table;
             IsPreviewMode = true;
 
         }
         private void HidePopup()
         {
             IsPreviewMode=false;
         }
                 
 
     }
 }
 
 
 

In the xml file we have define the attribute [@PopupVisible='True'] because we don’t want all the columns mentioned in the Columns.xml to be visible in Xamgrid, we just want the only columns which has this property should be visible and the rest should be not hence we are getting selected columns and we are filtering our columns in data table based on this.

10. Now run the project and you will get the below screen.

clip_image020

Click on GetData button and a popup will appear inside which we have our xamgrid with our data. Something like below screen and binding the data is successfully completed.clip_image022

Happy coding J

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Protect Your SharePoint