Back to Devexpress

Get Started with DevExpress Data Grid for .NET MAUI

maui-403351-data-grid-get-started.md

latest14.1 KB
Original Source

Get Started with DevExpress Data Grid for .NET MAUI

  • Sep 18, 2024
  • 8 minutes to read

This example allows you to get started with the DataGridView component – bind it to a data source and configure its columns.

View Example: Get Started with the DevExpress .NET MAUI Data Grid

Watch Video: Adding a Data Grid to Your .NET MAUI app using DevExpress Controls

Prerequisites

Refer to the following pages before you proceed with this Getting Started lesson:

1. Create a New .NET MAUI Application and Add a Data Grid

  1. Create a new .NET MAUI solution.

  2. Remove default content from the main page (MainPage.xaml) and event handlers from the code-behind file (MainPage.xaml.cs). Clear the application’s resource dictionary (App.xaml).

  3. Install the DevExpress.Maui.DataGrid package from your DevExpress NuGet feed.

  4. In the MauiProgram.cs file, call the the following UseDevExpress * methods to register handlers for the DevExpress DataGrid control:

  5. In the MainPage.xaml file, use the dx prefix to declare the http://schemas.devexpress.com/maui common namespace and add a DataGridView object to the ContentPage:

2. Create a Data Source

In this example, the grid is bound to a collection of Employee objects - EmployeeData. Create a Model.cs file with the following classes:

csharp
using System.Collections.ObjectModel;
using Microsoft.Maui.Controls;
using System;

namespace DataGridExample {
    public enum AccessLevel {
        Admin,
        User
    }

    public class Employee {
        string name;
        string resourceName;

        public string Name {
            get { return name; }
            set {
                name = value;
                if (Photo == null) {
                    resourceName = "DataGridExample.Images." + value.Replace(" ", "_") + ".jpg";
                    if (!String.IsNullOrEmpty(resourceName))
                        Photo = ImageSource.FromResource(resourceName);
                }
            }
        }

        public Employee(string name) {
            this.Name = name;
        }
        public ImageSource Photo { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime HireDate { get; set; }
        public string Position { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public AccessLevel Access { get; set; }
        public bool OnVacation { get; set; }
    }

    public class EmployeeData {
        void GenerateEmployees() {
            ObservableCollection<Employee> result = new ObservableCollection<Employee>();
            result.Add(
                new Employee("Nancy Davolio") {
                    BirthDate = new DateTime(1978, 12, 8),
                    HireDate = new DateTime(2005, 5, 1),
                    Position = "Sales Representative",
                    Address = "98122, 507 - 20th Ave. E. Apt. 2A, Seattle WA, USA",
                    Phone = "(206) 555-9857",
                    Access = AccessLevel.User,
                    OnVacation = false
                }
            );
            result.Add(
                new Employee("Andrew Fuller") {
                    BirthDate = new DateTime(1965, 2, 19),
                    HireDate = new DateTime(1992, 8, 14),
                    Position = "Vice President, Sales",
                    Address = "98401, 908 W. Capital Way, Tacoma WA, USA",
                    Phone = "(206) 555-9482",
                    Access = AccessLevel.Admin,
                    OnVacation = false
                }
            );
            result.Add(
                new Employee("Janet Leverling") {
                    BirthDate = new DateTime(1985, 8, 30),
                    HireDate = new DateTime(2002, 4, 1),
                    Position = "Sales Representative",
                    Address = "98033, 722 Moss Bay Blvd., Kirkland WA, USA",
                    Phone = "(206) 555-3412",
                    Access = AccessLevel.User,
                    OnVacation = false
                }
            );
            result.Add(
                new Employee("Margaret Peacock") {
                    BirthDate = new DateTime(1973, 9, 19),
                    HireDate = new DateTime(1993, 5, 3),
                    Position = "Sales Representative",
                    Address = "98052, 4110 Old Redmond Rd., Redmond WA, USA",
                    Phone = "(206) 555-8122",
                    Access = AccessLevel.User,
                    OnVacation = false
                }
            );
            result.Add(
                new Employee("Steven Buchanan") {
                    BirthDate = new DateTime(1955, 3, 4),
                    HireDate = new DateTime(1993, 10, 17),
                    Position = "Sales Manager",
                    Address = "SW1 8JR, 14 Garrett Hill, London, UK",
                    Phone = "(71) 555-4848",
                    Access = AccessLevel.User,
                    OnVacation = true
                }
            );
            result.Add(
                new Employee("Michael Suyama") {
                    BirthDate = new DateTime(1981, 7, 2),
                    HireDate = new DateTime(1999, 10, 17),
                    Position = "Sales Representative",
                    Address = "EC2 7JR, Coventry House Miner Rd., London, UK",
                    Phone = "(71) 555-7773",
                    Access = AccessLevel.User,
                    OnVacation = false
                }
            );
            result.Add(
                new Employee("Robert King") {
                    BirthDate = new DateTime(1960, 5, 29),
                    HireDate = new DateTime(1994, 1, 2),
                    Position = "Sales Representative",
                    Address = "RG1 9SP, Edgeham Hollow Winchester Way, London, UK",
                    Phone = "(71) 555-5598",
                    Access = AccessLevel.User,
                    OnVacation = false
                }
            );
            result.Add(
                new Employee("Laura Callahan") {
                    BirthDate = new DateTime(1985, 1, 9),
                    HireDate = new DateTime(2004, 3, 5),
                    Position = "Inside Sales Coordinator",
                    Address = "98105, 4726 - 11th Ave. N.E., Seattle WA, USA",
                    Phone = "(206) 555-1189",
                    Access = AccessLevel.User,
                    OnVacation = true
                }
            );
            result.Add(
                new Employee("Anne Dodsworth") {
                    BirthDate = new DateTime(1980, 1, 27),
                    HireDate = new DateTime(2004, 11, 15),
                    Position = "Sales Representative",
                    Address = "WG2 7LT, 7 Houndstooth Rd., London, UK",
                    Phone = "(71) 555-4444",
                    Access = AccessLevel.User,
                    OnVacation = false
                }
            );
            Employees = result;
        }

        public ObservableCollection<Employee> Employees { get; private set; }

        public EmployeeData() {
            GenerateEmployees();
        }
    }
}

Create a ViewModel.cs file and add a view model class:

csharp
using System.Collections.Generic;
using System.ComponentModel;

namespace DataGridExample {
    public class EmployeeDataViewModel : INotifyPropertyChanged {
        readonly EmployeeData data;

        public event PropertyChangedEventHandler PropertyChanged;
        public IReadOnlyList<Employee> Employees { get => data.Employees; }

        public EmployeeDataViewModel() {
            data = new EmployeeData();
        }

        protected void RaisePropertyChanged(string name) {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

3. Bind the Grid to Data

In the MainPage.xaml file:

  1. Assign an EmployeeDataViewModel object to the ContentPage.BindingContext property.
  2. Bind the DataGridView.ItemsSource property to the employee collection object that the EmployeeDataViewModel.Employees property returns.
xaml
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:dx="http://schemas.devexpress.com/maui"
             xmlns:local="clr-namespace:DataGridExample.ViewModels"
             x:Class="DataGridExample.MainPage">
    <ContentPage.BindingContext>
        <local:EmployeeDataViewModel/>
    </ContentPage.BindingContext>
    <dx:DataGridView ItemsSource="{Binding Employees}">
    </dx:DataGridView>
</ContentPage>

4. Specify Grid Columns

Do the following to specify a collection of grid columns:

  1. Create column objects and use the FieldName property to bind each column to a data source field.
  2. Add columns to the DataGridView.Columns collection in the order you want them to be displayed in the grid.

This tutorial creates the following grid columns:

  • Photo (ImageColumn) – displays photos of employees. Add images to a project as embedded resources.

  • Employee (TemplateColumn) – displays names, positions, and hire dates of employees.

  • Phone and Address (TextColumn) – display phone numbers and addresses of employees. The keyboard for text input appears when a user activates a cell to edit an employee’s phone number or address.

  • Birth Date (DateColumn) – displays birth dates of employees and allows users to edit dates.

  • Access Level (ComboBoxColumn) – displays employee access level and allows a user to select between predefined values (Admin or User) to change a cell value.

  • On Vacation (CheckBoxColumn) – specifies whether an employee is on leave. This column displays checkboxes in cells to display and manage Boolean values.

Use the DataGridView.EditorShowMode property to specify a gesture that invokes an in-place editor for a cell. The grid automatically defines an editor type depending on the type of a column to which a cell belongs (except for TemplateColumn).

xaml
<dx:DataGridView ItemsSource="{Binding Employees}"
                 EditorShowMode="DoubleTap">
    <dx:DataGridView.Columns>
        <dx:ImageColumn FieldName="Photo" Width="100"/>
        <dx:TemplateColumn FieldName="Name" Caption="Employee" MinWidth="200">
            <dx:TemplateColumn.DisplayTemplate>
                <DataTemplate>
                    <Grid VerticalOptions="Center" Padding="15, 0, 0, 0" RowDefinitions="Auto, Auto, Auto">
                        <Label Text="{Binding Item.Name}" FontSize="18" FontAttributes="Bold"
                            TextColor="{DynamicResource GridCellFontColor}" Grid.Row="0" />
                        <Label Text="{Binding Item.Position, StringFormat = 'Job Title: {0}'}"
                            FontSize="Small" TextColor="{DynamicResource GridCellFontColor}" 
                            Grid.Row="1"/>
                        <Label Text="{Binding Item.HireDate, StringFormat = 'Hire Date: {0:d}'}"
                            FontSize="Small" TextColor="{DynamicResource GridCellFontColor}" 
                            Grid.Row="2" />
                    </Grid>
                </DataTemplate>
            </dx:TemplateColumn.DisplayTemplate>
        </dx:TemplateColumn>
        <dx:TextColumn FieldName="Phone" 
                        MinWidth="130" VerticalContentAlignment="Center" />
        <dx:TextColumn FieldName="Address" 
                        MinWidth="150" VerticalContentAlignment="Center" />
        <dx:DateColumn FieldName="BirthDate" 
                        MinWidth="120" DisplayFormat="d" VerticalContentAlignment="Center"/>
        <dx:ComboBoxColumn FieldName="Access" Caption="Access Level" 
                            MinWidth="140" VerticalContentAlignment="Center"/>
        <dx:CheckBoxColumn FieldName="OnVacation" 
                            MinWidth="130" VerticalContentAlignment="Center"/>
    </dx:DataGridView.Columns>
</dx:DataGridView>

5. Enable Drag-and-Drop

The DataGridView supports drag-and-drop operations and allows users to reorder rows. Users should touch and hold a data row and then drag and drop the row to another position.

To enable drag-and-drop operations, set the AllowDragDropRows property to true.

xaml
<dx:DataGridView ItemsSource="{Binding Employees}"
                  EditorShowMode="DoubleTap"
                  AllowDragDropRows="True">
    <!-- Grid columns are here. -->
</dx:DataGridView>

See Also

.NET MAUI Data Grid: Examples