FlexGrid Samples > iTunes Sample > Grouping |
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 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 add three buttons above the grid: Artists, Albums, and Songs. The event handlers for these buttons are implemented as follows:
C# |
Copy Code
|
---|---|
// 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); } |
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:
C# |
Copy Code
|
---|---|
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 starts by retrieving the grid's RowCollection class and implements the same DeferNotifications mechanism used by the ICollectionView interface. This mechanism is similar to the BeginUpdate and 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.