Here's what I came up with. It provides flexibility to expand or collapse all levels or specific levels. (This could be refactored to remove duplicate code, if desired.) To expand or collapse all groups at all levels in a single call, simply pass in "0" for the groupingLevel parameter and "true" for the collapseAllSublevels parameter. By using a HashSet, duplicates are automatically eliminated from the "groups" collection.
/// <summary>
/// Collapse all groups at a specific grouping level.
/// </summary>
/// <param name="groupingLevel">The grouping level to collapse. Level 0 is the top level. Level 1 is the next level, etc.</param>
/// <param name="collapseAllSublevels">Indicates whether levels below the specified level should also be collapsed. The default is "false".</param>
private void CollapseGroups(int groupingLevel, bool collapseAllSublevels = false)
{
if (myGrid.ItemsSource == null)
return;
HashSet<CollectionViewGroup> groups = new HashSet<CollectionViewGroup>();
foreach (object item in myGrid.ItemsSource)
groups.Add(myGrid.GetGroupFromItem(item, groupingLevel));
foreach (CollectionViewGroup group in groups)
myGrid.CollapseRowGroup(group, collapseAllSublevels);
}
/// <summary>
/// Expand all groups at a specific grouping level.
/// </summary>
/// <param name="groupingLevel">The grouping level to expand. Level 0 is the top level. Level 1 is the next level, etc.</param>
/// <param name="expandAllSublevels">Indicates whether levels below the specified level should also be expanded. The default is "false".</param>
private void ExpandGroups(int groupingLevel, bool expandAllSublevels = false)
{
if (myGrid.ItemsSource == null)
return;
HashSet<CollectionViewGroup> groups = new HashSet<CollectionViewGroup>();
foreach (object item in myGrid.ItemsSource)
groups.Add(myGrid.GetGroupFromItem(item, groupingLevel));
foreach (CollectionViewGroup group in groups)
myGrid.ExpandRowGroup(group, expandAllSublevels);
}