How to clear selection in a button click using MVVM in MAUI DataGrid (SfDataGrid)?
The .NET MAUI DataGrid (SfDataGrid) allows you to programmatically clear the selection by setting the SelectionMode to None. You can clear the selection with a button click in MVVM by adding a command and CommandParameter to the button.
Refer to the code example below in which a Command is triggered for clearing the selection in SfDataGrid. The reference of SfDataGrid is passed as a CommandParameter to a button to clear the selection in the view model.
XAML
<StackLayout> <Button Text="Clear Selection" Command="{Binding ClearSelection}" CommandParameter="{x:Reference dataGrid}" /> <syncfusion:SfDataGrid x:Name="dataGrid" ItemsSource="{Binding OrdersInfo}" AutoGenerateColumnsMode="None" SelectionMode="Multiple" ColumnWidthMode="Auto" VerticalOptions="FillAndExpand"> <syncfusion:SfDataGrid.Columns> <syncfusion:DataGridNumericColumn MappingName="OrderID" HeaderText="Order ID" Format="d" /> <syncfusion:DataGridTextColumn MappingName="CustomerID" HeaderText="Customer ID"/> <syncfusion:DataGridTextColumn MappingName="Freight" /> <syncfusion:DataGridTextColumn MappingName="Country"/> </syncfusion:SfDataGrid.Columns> </syncfusion:SfDataGrid> </StackLayout>
C#
public class ViewModel : INotifyPropertyChanged { private Command clearSelection; public Command ClearSelection { get { return clearSelection; } } private void ClearSelectionCommand(object obj) { var dataGrid = obj as SfDataGrid; dataGrid.SelectionMode = DataGridSelectionMode.None; } OrderInfoRepository order; public ViewModel() { order = new OrderInfoRepository(); clearSelection = new Command(ClearSelectionCommand); SetRowstoGenerate(50); } private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; } } public void SetRowstoGenerate(int count) { ordersInfo = order.GetOrderDetails(count); } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
Output
Download the complete sample from GitHub.
Conclusion
I hope you enjoyed learning how to clear selection in a button click using MVVM in MAUI DataGrid (SfDataGrid)
You can refer to our .NET MAUI DataGrid feature tour page to learn about its other groundbreaking feature representations. Explore our .NET MAUI DataGrid Documentation to understand how to present and manipulate data.
For current customers, check out our .NET MAUI components from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI DataGrid and other .NET MAUI components.
Please let us know in the comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!