How to maintain the group expanded states while ungrouping and grouping the columns at runtime in WPF DataGrid (SfDataGrid)?
WPF DataGrid (SfDataGrid) allows you to maintain the expanded state of the group while ungrouping and grouping the columns at runtime by handling the events SfDataGrid.View.CollectionChanged, SfDataGrid.GroupExpanded and SfDataGrid.GroupCollapsed.
public Dictionary<string, bool> GroupStates = new Dictionary<string, bool>(); public MainWindow() { InitializeComponent(); this.dataGrid.Loaded += OnDataGrid_Loaded; } private void OnDataGrid_Loaded(object sender, RoutedEventArgs e) { this.dataGrid.View.CollectionChanged += OnView_CollectionChanged; this.dataGrid.GroupExpanded += OnDataGrid_GroupExpanded; this.dataGrid.GroupCollapsed += OnDataGrid_GroupCollapsed; } private void OnDataGrid_GroupCollapsed(object sender, GroupChangedEventArgs e) { GroupStates[e.Group.Key.ToString()] = false; } private void OnDataGrid_GroupExpanded(object sender, GroupChangedEventArgs e) { GroupStates[e.Group.Key.ToString()] = true; } private void OnView_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { var collectionViewWrapper = sender as GridQueryableCollectionViewWrapper; if (collectionViewWrapper != null) { if (collectionViewWrapper.Groups != null && collectionViewWrapper.Groups.Count > 0) { foreach (var group in collectionViewWrapper.Groups) { var grp = group as Group; var key = grp.Key.ToString(); if (GroupStates.ContainsKey(key)) { grp.IsExpanded = GroupStates[key]; while (!grp.IsBottomLevel) { var innergroups = grp.Groups; if (innergroups != null && innergroups.Count > 0) { foreach (var innerGroup in innergroups) { if (GroupStates.ContainsKey(innerGroup.Key.ToString())) innerGroup.IsExpanded = GroupStates[innerGroup.Key.ToString()]; else GroupStates.Add(innerGroup.Key.ToString(), innerGroup.IsExpanded); grp = innerGroup; } } } } else { GroupStates.Add(key, grp.IsExpanded); } } } } }
Take a moment to peruse the documentation, where you can find about grouping in SfDataGrid, with code examples.
You can download the example from GitHub
Conclusion
I hope you enjoyed learning about how to to maintain group expanded states in WPF DataGrid.
You
can refer to our WPF
DataGrid feature tour
page to know
about its other groundbreaking feature representations. You can also
explore our WPF
DataGrid documentation to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!