Category / Section
How to toggle selection mode with tap events in .NET MAUI DataGrid?
6 mins read
This article demonstrates how to toggle selection mode with tap events .NET MAUI DataGrid (SfDataGrid).
The SfDataGrid component uses event handlers to manage transitions between modes. In its normal state, it responds to single taps by displaying information about the tapped row. A long press switches the grid to selection mode, allowing multiple items to be selected with visual indicators that reflect the current state.
Xaml
<ContentPage.Content>
<Grid RowDefinitions="Auto,*,Auto">
<HorizontalStackLayout Grid.Row="0" Spacing="10" Padding="10">
<Button x:Name="exitSelectionButton"
Text="Exit Selection Mode"
IsVisible="false"
Clicked="OnExitSelectionMode" />
</HorizontalStackLayout>
<syncfusion:SfDataGrid x:Name="sfdatagrid"
Grid.Row="1"
SelectionMode="None"
SelectionUnit="Row"
ItemsSource="{Binding Employees}">
<syncfusion:SfDataGrid.Columns>
<syncfusion:DataGridTextColumn MappingName="EmployeeID"
HeaderText="Employee ID" />
<syncfusion:DataGridTextColumn MappingName="Name"
HeaderText="Name" />
<syncfusion:DataGridTextColumn MappingName="IDNumber"
HeaderText="IDNumber" />
<syncfusion:DataGridNumericColumn MappingName="ContactID"
HeaderText="ContactID" />
<syncfusion:DataGridTextColumn MappingName="SickLeaveHours"
HeaderText="SLH" />
<syncfusion:DataGridTextColumn Format="d"
MappingName="HireDate"
HeaderText="HireDate" />
<syncfusion:DataGridTextColumn Format="d"
MappingName="BirthDate"
HeaderText="DOB" />
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
</Grid>
</ContentPage.Content>
Xaml.cs
public partial class MainPage : ContentPage
{
private bool _isInSelectionState = false;
public MainPage()
{
InitializeComponent();
SetNormalState();
sfdatagrid.CellTapped += OnDataGridCellTapped;
sfdatagrid.CellLongPress += OnDataGridCellLongPress;
}
private void SetNormalState()
{
_isInSelectionState = false;
sfdatagrid.SelectionMode = DataGridSelectionMode.None;
this.Title = "Data Grid (Normal State)";
exitSelectionButton.IsVisible = false;
}
private void SetSelectionState()
{
_isInSelectionState = true;
sfdatagrid.SelectionMode = DataGridSelectionMode.Multiple;
this.Title = "Data Grid (Selection State)";
exitSelectionButton.IsVisible = true;
}
private void OnDataGridCellTapped(object sender, DataGridCellTappedEventArgs e)
{
if (!_isInSelectionState)
{
var employee = e.RowData as Employee;
if (employee != null)
{
DisplayAlert("Row Tapped",
$"You tapped on {employee.Name} (ID: {employee.EmployeeID})",
"OK");
}
}
}
private void OnDataGridCellLongPress(object sender, DataGridCellLongPressEventArgs e)
{
if (!_isInSelectionState)
{
SetSelectionState();
var rowData = e.RowData;
if (rowData != null )
{
sfdatagrid.SelectedRows.Add(rowData);
}
}
}
private void OnExitSelectionMode(object sender, EventArgs e)
{
SetNormalState();
}
}
You can download this example on GitHub.