Articles in this section
Category / Section

How to maintain only one group in expand state in SfListView?

1 min read

SfListView allows you to maintain only one group in expanded state by handling the GroupExpanding event. If any group is expanded, then collapse the remaining groups by comparing with expanded group. Please refer the below code snippet.

C#

public partial class MainPage : ContentPage
{
    GroupResult expandedGroup;
 
    public MainPage()
    {
        InitializeComponent();
        listView.DataSource.SortDescriptors.Add(new SortDescriptor() { PropertyName = "ContactName", Direction = ListSortDirection.Ascending });
        listView.DataSource.GroupDescriptors.Add(new GroupDescriptor()
        {
            PropertyName = "ContactName",
            KeySelector = (object obj1) =>
            {
                var item = (obj1 as Contacts);
                return item.ContactName[0].ToString();
            },
        });
        listView.GroupExpanding += ListView_GroupExpanding;
    }
 
    private void ListView_GroupExpanding(object sender, GroupExpandCollapseChangingEventArgs e)
    {
        if (e.Groups.Count > 0)
        {
            var group = e.Groups[0];
            if (expandedGroup == null || group.Key != expandedGroup.Key)
            {
                foreach (var otherGroup in listView.DataSource.Groups)
                {
                    if (group.Key != otherGroup.Key)
                    {
                        listView.CollapseGroup(otherGroup);
                    }
                }
                expandedGroup = group;
                listView.ExpandGroup(expandedGroup);
            }
        }
    }
 
    private void listView_Loaded(object sender, ListViewLoadedEventArgs e)
    {
        listView.CollapseAll();
        var group = listView.DataSource.Groups[0];
        listView.ExpandGroup(group);
    }
}

 

In this above code snippet, the first group is in expanded state, which is maintain by expandedGroup field and remaining groups are collapsed when SfListView is loaded. If any other group is expanded, based on comparing the expandedGroup field, remaining groups gets collapsed.

Click here to download the sample.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied