Selecting the First Row in DataGrid by Default Using MVVM in UI for .NET MAUI
Environment
Version | Product | Author |
---|---|---|
11.1.0 | DataGrid for .NET MAUI | Dobrinka Yordanova |
Description
I want to select the first row in the DataGrid component by default using an MVVM approach.
This knowledge base article also answers the following questions:
- How to set a default selected row in the UI for .NET MAUI DataGrid?
- How to bind the DataGrid's
SelectedItem
property in MVVM? - How to programmatically select the first row in a DataGrid?
Solution
To select the first row by default, bind the SelectedItem
property of the DataGrid to a property in the ViewModel
and set its value to the first item in the collection.
- Define the
ViewModel
: Create aSelectedItem
property in theViewModel
to hold the selected row.
private MyItem selectedItem;
public ObservableCollection<MyItem> Items { get; set; }
public MyItem SelectedItem
{
get => this.selectedItem;
set
{
if (this.selectedItem != value)
{
this.selectedItem = value;
OnPropertyChanged(nameof(this.SelectedItem));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) =>
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
This setup ensures that changes to the SelectedItem
property automatically notify the UI to refresh.
- Set the Default Selection: Assign the first item in the collection to the
SelectedItem
property.
public MainViewModel()
{
this.Items = new ObservableCollection<MyItem>
{
new MyItem { Name = "Item 1", Description = "First item description" },
new MyItem { Name = "Item 2", Description = "Second item description" },
new MyItem { Name = "Item 3", Description = "Third item description" }
};
this.SelectedItem = this.Items[0]; // Select the first item.
}
- Bind the ViewModel to the DataGrid: In XAML, bind the
SelectedItem
property of the DataGrid to theViewModel
and set the binding mode toTwoWay
.
<telerik:RadDataGrid
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
This approach ensures that the first row in the DataGrid is selected by default.