How to format column using converter in .NET MAUI DataGrid?
This article explains how to format a column using a converter in .NET MAUI DataGrid.
The column can be formatted by using a Converter in the DisplayBinding.
XAML
Utilize the Converter property within the binding to format the column.
<ContentPage.Resources>
<converter:CurrencyFormatConverter x:Key="currencyFormatConverter"/>
</ContentPage.Resources>
<dataGrid:SfDataGrid x:Name="dataGrid"
ColumnWidthMode="Auto"
GridLinesVisibility="Both"
HeaderGridLinesVisibility="Both"
ItemsSource="{Binding Employees}">
<dataGrid:SfDataGrid.Columns>
<dataGrid:DataGridNumericColumn MappingName="EmployeeID" HeaderText="Employee ID"/>
<dataGrid:DataGridTextColumn MappingName="Name" />
<dataGrid:DataGridNumericColumn MappingName="Salary"
HeaderText="Salary"
DisplayBinding="{Binding Path=Salary,Converter={StaticResource currencyFormatConverter}}"/>
</dataGrid:SfDataGrid.Columns>
</dataGrid:SfDataGrid>
C#
public MainPage()
{
InitializeComponent();
//Equivalent to the code in the XAMl section
DataGridTextColumn salaryColumn = new DataGridTextColumn() { MappingName = "Salary", HeaderText = "Salary" };
salaryColumn.DisplayBinding = new Binding() { Path = "Salary", Converter = new CurrencyFormatConverter() };
dataGrid.Columns.Add(salaryColumn);
}
CurrencyFormatConverter
public class CurrencyFormatConverter : IValueConverter
{
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return string.Format("{0:C}", value);
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The following screenshot shows how to format a column using the converter in .NET MAUI DataGrid.
Download the complete sample from GitHub
Looking for the full .NET MAUI Data Grid component overview, features, pricing, and documentation? Visit the .NET MAUI DataGrid feature tour page