I previously wrote about DataGrid grouping using the declarative model of adding GroupDescriptors. Unfortunately that feature (the declarative part) never made it to the release of Silverlight 3. It was pointed out to me that I should update that post and it has been on my //TODO list for a while. Here’s an update…
First, I’m still using a sample data class of Person as my test data:
Then my XAML is a simple DataGrid (make sure to add assembly references to your project to System.Windows.Controls.Data):
Notice the xmlns:datacontrols declaration at the top.
Now since we can’t do the grouping declaratively as in my previous sample with Silverlight 3 beta, here’s how we could do it. In Silverlight 3 you have access to PagedCollectionView (add a reference to System.Windows.Data to get it). This is a view that enables you to add sort and group descriptors. In my initial loading code I instantiate a new PagedCollectionView passing in my List<Person> as the enumerable type. I then set a default grouping on it.
Then I can wire up a quick and dirty (just for demonstration purposes) ComboBox to show changing the grouping (or perhaps adding another one if you’d like):
You see we are just changing the PagedCollectionView and not the DataGrid. The binding that exists between them already understands what to do – so we just have to change the data source, not the control displaying the source. Put them all together and the running application shows the grouping:
Hopefully this helps clarify the change from SL3 beta and apologies for the delay in updating what is a common sample request. Who knows, maybe in future versions the declarative model will come back :-). Here’s the code for the above if you’d like to see it: DataGridGroupingUpdated.zip