这就是我想出的。它提供了扩展或折叠所有级别或特定级别的灵活性。(如果需要,可以重构以删除重复代码。)要在单个调用中展开或折叠所有级别的所有组,只需为 groupingLevel 参数传入“0”,为 collapseAllSublevels 参数传入“true” 。通过使用 HashSet,可以自动从“组”集合中消除重复项。
/// <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);
}