Category / Section
How to retain groups after updating the ItemsSource in Xamarin.Forms ListView using MVVM
1 min read
The Xamarin.Forms SfListView allows you to maintain groups after refreshing the ItemsSource with MVVM.
C#
Define the DataSource property in the ViewModel class. The GroupDescriptors can be added to the ViewModel DataSource property.
public class ContactsViewModel : INotifyPropertyChanged
{
public DataSource ListDataSource { get; set; }
public ObservableCollection<Contacts> ContactsInfo
{
get { return contactsInfo; }
set { contactsInfo = value; this.OnPropertyChanged("ContactsInfo"); }
}
public ContactsViewModel()
{
ListDataSource = new DataSource();
ListDataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactType" });
GenerateInfo();
}
}
XAML
Bind the ViewModel DataSource to the SfListView.DataSource property.
<syncfusion:SfListView x:Name="listView" ItemSize="60" DataSource="{Binding ListDataSource}" ItemsSource="{Binding ContactsInfo}">
<syncfusion:SfListView.ItemTemplate >
<DataTemplate>
...
</DataTemplate>
</syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>
C#
When the ItemsSource is changed, the DataSource.GroupDescriptors will be cleared by default. However, you can maintain the grouping by adding the GroupDescriptor while updating the ItemsSource.
public class ContactsViewModel : INotifyPropertyChanged
{
public Command RefreshCommand { get; set; }
public ContactsViewModel()
{
RefreshCommand = new Command(RefreshItemsSource);
}
private void RefreshItemsSource(object obj)
{
if(ContactsInfo.Count > 0)
{
ContactsInfo.Clear();
ContactsInfo = null;
}
GenerateInfo();
ListDataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactType" });
}
}
