We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to Expand or Collapse a single SfListView Group with MVVM

I am using a SfListView to group a collection and I would like to know if it is possible to Expand or Collapse a single group using a ViewModel. I would like to Expand the first group in my collection by default after the data is initially fetched from my database within the ViewModel command that executes this (if possible). Additionally, the DataSource that is binded to the SfListView will frequently be refreshed, so I would like to have a way to keep track of what groups are currently expanded and keep these groups open whenever the data is refreshed from my ViewModel. I'm sure that there are many people who would like to know if this can be done as well. The documentation doesn't mention anything about Expanding or Collapsing groups using MVVM.

Thanks,

Bryson


1 Reply

SV Suja Venkatesan Syncfusion Team November 11, 2022 02:17 PM UTC

The ExpandGroups and CollapseGroups methods in SfListView allow you to programmatically expand and collapse the group. Accessing XAML controls from ViewModel is not recommended because it violates the MVVM rule. You can meet your requirements by using MessagingCenter in Xamarin.Forms. Publish an expand message in which group you need to expand by passing it as the third parameter in the Send method of MessagingCenter, as shown in the code snippet below.


Code Snippet:

//ViewModel.cs

private void TappedCommandMethod(object obj)

{

  MessagingCenter.Send<BookInfoRepository,int>(this, "Expand",0);

}


Using MessagingCenter, subscribe to a message that contains group information.  in the ListView behavior and pass that group detail to the ExpandGroup method, as shown in the code snippet below.

//ListViewBehavior.cs

protected override void OnAttachedTo(SfListView bindable)

        {

            MessagingCenter.Subscribe<BookInfoRepository, int>(this, "Expand", async (sender, arg) =>

            {

                var group = bindable.DataSource.Groups[arg];

                bindable.ExpandGroup(group);

            });

            base.OnAttachedTo(bindable);

        }


Please refer to our user guidelines documentation regarding programmatic expanding and collapsing in the below link.

UG link: https://help.syncfusion.com/xamarin/listview/grouping#programmatic-expand-and-collapse


And, also refer MessagingCenter in Xamarin.Forms in the below reference link.

Reference link: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center


We have attached a runnable based on your requirement for your reference. Please let us know if you need any further assistance.



Attachment: GettingStarted_834ffb84.zip

Loader.
Live Chat Icon For mobile
Up arrow icon