Property Group Descriptor for .NET MAUI DataGrid
The PropertyGroupDescriptor
is used to group the data in a DataGrid by property from the class that defines your objects.
To use the PropertyGroupDescriptor
, you have to set its PropertyName
(string
) property, which gets or sets the name of the property that is used to retrieve the key by which to group.
You can sort the groups in ascending or descending order by using the
SortOrder
property.
Let's, for example, have the following business object:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
Add a sample ViewModel
class with a collection of Person
objects:
public class ViewModel : NotifyPropertyChangedBase
{
private DataGridCellInfo cell;
public ViewModel()
{
this.People = new ObservableCollection<Person>()
{
new Person { Name = "Kiko", Age = 23, Department = "Production" },
new Person { Name = "Jerry", Age = 23, Department = "Accounting and Finance"},
new Person { Name = "Ethan", Age = 51, Department = "Marketing" },
new Person { Name = "Isabella", Age = 25, Department = "Marketing" },
new Person { Name = "Joshua", Age = 45, Department = "Production" },
new Person { Name = "Logan", Age = 26, Department = "Production"},
new Person { Name = "Aaron", Age = 32, Department = "Production" },
new Person { Name = "Elena", Age = 37, Department = "Accounting and Finance"},
new Person { Name = "Ross", Age = 30, Department = "Marketing" },
};
}
public DataGridCellInfo Cell
{
get => this.cell;
set
{
if (this.cell != value)
{
this.cell = value;
this.OnPropertyChanged();
}
}
}
public ObservableCollection<Person> People { get; set; }
}
Define the DataGrid
:
<telerik:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding People}">
<telerik:RadDataGrid.GroupHeaderTemplate>
<DataTemplate>
<HorizontalStackLayout Margin="5,0,0,0" VerticalOptions="Center" >
<Label Text="Employees working in: "
TextColor="DarkBlue"
FontSize="{OnPlatform MacCatalyst=Default, Default=Small}" />
<Label Text="{Binding Group.Key}"
FontAttributes="Bold"
TextColor="DarkBlue"
FontSize="{OnPlatform MacCatalyst=Default, Default=Small}" />
</HorizontalStackLayout>
</DataTemplate>
</telerik:RadDataGrid.GroupHeaderTemplate>
</telerik:RadDataGrid>
All that is left is to set is the ViewModel
as BindingContext
of the page:
this.BindingContext = new ViewModel();
Apply the PropertyGroupDescriptor
:
this.dataGrid.GroupDescriptors.Add(new Telerik.Maui.Controls.Compatibility.Common.Data.PropertyGroupDescriptor()
{
PropertyName="Department"
});
Here is how the DataGrid looks when it is grouped: