Xamarin.Forms - DataGrid

Introduction

 
The DataGrid is a format or architecture to show a set of data in the user interface. In Xamarin Forms there is no default DataGrid control, so we need to install “DataGrid.Xamarin.Forms” dependency.
 
Xamarin.Forms - DataGrid
 
Let’s start to create new Xamarin.Forms application in Visual Studio for Mac
 
Xamarin.Forms - DataGrid
 
Once the project is created, install “Xamarin.Forms.DataGrid” dependency by going to the Solution Explorer >> right-click and select “Manage NuGet Packages” >> in the new dialog, in the top right corner search for  “Xamarin.Forms.DataGrid” and install it.
 
Xamarin.Forms - DataGrid
 
Create an MVVM folder structure, create a Professional.cs model class under the Model folder. For that, open Solution Explorer >> right-click the Model folder and select Add > new class and give name as Professional.cs. The class code is given below. 
  1. using System;  
  2. namespace XFDataGrid.Models  
  3. {  
  4.     public class Professional  
  5.     {  
  6.         public string Id { getset; }  
  7.         public string Name { getset; }  
  8.         public string Desigination { getset; }  
  9.         public string Domain { getset; }  
  10.         public string Experience { getset; }  
  11.     }  
  12. }  
Now, create another DummyProfessionalData.cs class under the Utils folder for dummy data. This class used for creating dummy data and code is given here.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using XFDataGrid.Models;  
  4.   
  5. namespace XFDataGrid.Utils  
  6. {  
  7.     public static class DummyProfessionalData  
  8.     {  
  9.         public static List<Professional> GetProfessionals()  
  10.         {  
  11.             var data = new List<Professional>();  
  12.             var person = new Professional()  
  13.             {  
  14.                 Id = "3",  
  15.                 Name = "Monkey",  
  16.                 Desigination = "Developer",  
  17.                 Domain = "Mobile",  
  18.                 Experience = "1"  
  19.             };  
  20.   
  21.             for (int i = 0; i < 10; i++)  
  22.             {  
  23.                 data.Add(person);  
  24.   
  25.             }  
  26.             return data;  
  27.         }  
  28.     }  
  29. }  
Next, Create MainPageViewModel.cs class under ViewModel folder and write the below code. Here, List and IsRefreshing properties and refresh command are written, and when the user swipes top to bottom, the refresh command will execute and refresh the UI with updated data. INotifyPropertyChanged property is also implemented to invoke the UI with new Data. The Professional Property is for single data selection.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Threading.Tasks;  
  5. using System.Windows.Input;  
  6. using Xamarin.Forms;  
  7. using XFDataGrid.Models;  
  8. using XFDataGrid.Utils;  
  9.   
  10. namespace XFDataGrid.ViewModels  
  11. {  
  12.     public class MainPageViewModel : INotifyPropertyChanged  
  13.     {  
  14.         private List<Professional> _professionals;  
  15.         private Professional _selectedProfessional;  
  16.         private bool _isRefreshing;  
  17.   
  18.         public List<Professional> Professionals  
  19.         {  
  20.             get  
  21.             {  
  22.                 return _professionals;  
  23.             }  
  24.             set  
  25.             {  
  26.                 _professionals = value;  
  27.                 OnPropertyChanged(nameof(Professionals));  
  28.             }  
  29.         }  
  30.         public Professional SelectedProfesstional  
  31.         {  
  32.             get  
  33.             {  
  34.                 return _selectedProfessional;  
  35.             }  
  36.             set  
  37.             {  
  38.                 _selectedProfessional = value;  
  39.                 OnPropertyChanged(nameof(SelectedProfesstional));  
  40.             }  
  41.         }  
  42.   
  43.         public bool IsRefreshing  
  44.         {  
  45.             get  
  46.             {  
  47.                 return _isRefreshing;  
  48.             }  
  49.             set  
  50.             {  
  51.                 _isRefreshing = value;  
  52.                 OnPropertyChanged(nameof(IsRefreshing));  
  53.             }  
  54.         }  
  55.   
  56.         public ICommand RefreshCommand { getset; }  
  57.   
  58.         public MainPageViewModel()  
  59.         {  
  60.             Professionals = DummyProfessionalData.GetProfessionals();  
  61.             RefreshCommand = new Command(CmdRefresh);  
  62.         }  
  63.   
  64.         private async void CmdRefresh()  
  65.         {  
  66.             IsRefreshing = true;  
  67.             await Task.Delay(3000);  
  68.             IsRefreshing = false;  
  69.         }  
  70.   
  71.         public event PropertyChangedEventHandler PropertyChanged;  
  72.   
  73.         private void OnPropertyChanged(string property)  
  74.         {  
  75.             if (PropertyChanged != null)  
  76.                 PropertyChanged(thisnew PropertyChangedEventArgs(property));  
  77.         }  
  78.     }  
  79. }  
After that open MainPage.xaml page and start our UI design. First, we call DataGrid namespace as dg and design our columns with Title, bind the PropertyName and width size. Bind ItemSource, SelectedItem, refershCommand. This page design code is given below.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:d="http://xamarin.com/schemas/2014/forms/design"  
  5.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.              xmlns:dg="clr-namespace:Xamarin.Forms.DataGrid;assembly=Xamarin.Forms.DataGrid"  
  7.              x:Class="XFDataGrid.MainPage">  
  8.     <ContentView>  
  9.         <!-- Place new controls here -->  
  10.         <dg:DataGrid ItemsSource="{Binding Professionals}" SelectionEnabled="True" SelectedItem="{Binding SelectedProfesstional}" RowHeight="70" HeaderHeight="50"  
  11.                     BorderColor="#CCCCCC" HeaderBackground="#E0E6F8" PullToRefreshCommand="{Binding RefreshCommand}" IsRefreshing="{Binding IsRefreshing}" ActiveRowColor="#8899AA">  
  12.             <x:Arguments>  
  13.                 <ListViewCachingStrategy>RetainElement</ListViewCachingStrategy>  
  14.             </x:Arguments>  
  15.             <dg:DataGrid.HeaderFontSize>  
  16.                 <OnIdiom x:TypeArguments="x:Double">  
  17.                     <OnIdiom.Tablet>15</OnIdiom.Tablet>  
  18.                     <OnIdiom.Phone>12</OnIdiom.Phone>  
  19.                 </OnIdiom>  
  20.             </dg:DataGrid.HeaderFontSize>  
  21.             <dg:DataGrid.Columns>  
  22.                 <dg:DataGridColumn Title="ID" PropertyName="Id" Width="1*"></dg:DataGridColumn>  
  23.                 <dg:DataGridColumn PropertyName="Name" Width="2*">  
  24.                     <dg:DataGridColumn.FormattedTitle>  
  25.                         <FormattedString>  
  26.                             <Span Text="Name" FontSize="13" TextColor="Black" FontAttributes="Bold"/>  
  27.                         </FormattedString>  
  28.                     </dg:DataGridColumn.FormattedTitle>  
  29.                 </dg:DataGridColumn>  
  30.                 <dg:DataGridColumn Title="Desigination" PropertyName="Desigination" Width="2*"/>  
  31.                 <dg:DataGridColumn Title="Domain" PropertyName="Domain" Width="2*"/>  
  32.                 <dg:DataGridColumn Title="Exp" PropertyName="Experience" Width="1*"/>  
  33.             </dg:DataGrid.Columns>  
  34.             <dg:DataGrid.RowsBackgroundColorPalette>  
  35.                 <dg:PaletteCollection>  
  36.                     <Color>#F2F2F2</Color>  
  37.                     <Color>#FFFFFF</Color>  
  38.                 </dg:PaletteCollection>  
  39.             </dg:DataGrid.RowsBackgroundColorPalette>  
  40.         </dg:DataGrid>  
  41.     </ContentView>  
  42. </ContentPage>  
Next open MainPage.xaml.cs and set BindingContext is MainPageViewModel as we done already. The source code is here.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using Xamarin.Forms;  
  8. using XFDataGrid.ViewModels;  
  9.   
  10. namespace XFDataGrid  
  11. {  
  12.     // Learn more about making custom code visible in the Xamarin.Forms previewer  
  13.     // by visiting https://aka.ms/xamarinforms-previewer  
  14.     [DesignTimeVisible(false)]  
  15.     public partial class MainPage : ContentPage  
  16.     {  
  17.         public MainPage()  
  18.         {  
  19.             InitializeComponent();  
  20.             BindingContext = new MainPageViewModel();  
  21.         }  
  22.     }  
  23. }  
Finally, initialize DataComponent in App Startup of App.xaml.cs class like the  below code. 
  1. using System;  
  2. using Xamarin.Forms;  
  3. using Xamarin.Forms.Xaml;  
  4.   
  5. namespace XFDataGrid  
  6. {  
  7.     public partial class App : Application  
  8.     {  
  9.         public App()  
  10.         {  
  11.             Xamarin.Forms.DataGrid.DataGridComponent.Init();  
  12.   
  13.             InitializeComponent();  
  14.   
  15.             MainPage = new MainPage();  
  16.         }  
  17.   
  18.         protected override void OnStart()  
  19.         {  
  20.         }  
  21.   
  22.         protected override void OnSleep()  
  23.         {  
  24.         }  
  25.   
  26.         protected override void OnResume()  
  27.         {  
  28.         }  
  29.     }  
  30. }  
Now, run your application and output like the below screenshot.
Xamarin.Forms - DataGrid
 
The full source code is here - GitHub 
 

Conclusion

 
I hope you all now understand how to use DataGrid in Xamarin.Forms and this blog is helpful for all. Thanks for reading. 


Similar Articles