Grouping

You probably noticed that the data binding code already took care of the basic grouping functionality by populating the GroupDescriptions property on our data source. This is enough for the grid to group the songs by album and artist and present collapsible group rows with some basic information about the group.

Let's take the grouping functionality a step further by adding buttons that will automatically collapse or expand the catalog to show only artists (fully collapsed groups), artists and albums (intermediate state), or artists, albums and songs (fully expanded groups).

To accomplish this, we added three buttons above the grid: Artists, Albums, and Songs. The event handlers for these buttons are implemented as follows:

// collapse/expand groups
void _btnShowArtists_Click(object sender, RoutedEventArgs e)
{
  ShowOutline(0);
}
void _btnShowAlbums_Click(object sender, RoutedEventArgs e)
{
  ShowOutline(1);
}
void _btnShowSongs_Click(object sender, RoutedEventArgs e)
{
  ShowOutline(int.MaxValue);
}

As you can see, all event handlers use the same ShowOutline helper method. The first collapses all level zero group rows (artists); the second expands level zero groups (artists) and collapses level one (albums); the last expands all group rows. Here is the implementation of the ShowOutline method:

void ShowOutline(int level)
{
  var rows = _flexiTunes.Rows;
  using (rows.DeferNotifications())
  {
    foreach (var gr in rows.OfType<GroupRow>())
    {
      gr.IsCollapsed = gr.Level >= level;
    }
  }
}

The method is very simple. It starts by retrieving the grid's RowCollection class implements the same DeferNotifications mechanism used by the ICollectionView interface. This mechanism is similar to the BeginUpdate/EndUpdate pattern common in WinForms applications, and improves performance significantly.

Next, the code uses the LINQ OfType operator to retrieve all GroupRow objects from the Rows collection. This automatically excludes regular rows and allows us to check the level of every group row and update its IsCollapsed state based on the level of each group row.


Send us comments about this topic.
Copyright © GrapeCity, inc. All rights reserved.