Collapsing groups in Silverlight Datagrid
April 22, 2009 2 Comments
One of my friends commented on “Missing functionality” of collapsing the groups in silverlight 3.0 datagrid.
I decided to blog this piece as i realized that though it is obvious to me “how this will work”, no blog has yet been dedicated to this.
so here it goes..
The problem: Display the datagrid so that all the groups are NOT expanded.
here is a snapshot. As you may observe, By default, every group is expanded (which may clutter the UI a bit)

It should look like (one level collapsed) :

or fully collapsed

Here is the XAML: Just for a more complex scenario(and to show how grouping may be done via XAML or C# code behind/ or both), we have used grouping Dept via XAML and via gender using C#.
| <StackPanel>
<TextBlock Text=”Expand/Collapse Datagrid Demo ” Style=”{StaticResource HeaderTextStyle}”/> <StackPanel Style=”{StaticResource ContentTextPanelStyle}” Orientation=”Horizontal”> </cm:PropertyGroupDescription> </StackPanel> |
and below is the codebehind:
Note the code in bold; specially the line DataContext = new PagedCollectionView(GetPeople());
which binda data to grid. Also pay attention to CollapseRowGroup() and ExpandRowGroup()
| public HomePage() { InitializeComponent(); MyGrid.GroupDescriptions.Add(new PropertyGroupDescription(“Gender”)); private void Button_Click(object sender, RoutedEventArgs e) } private void btnOneLevel_Click(object sender, RoutedEventArgs e) // Executes when the user navigates to this page. List<Person> peeps = new List<Person>(); peeps.Add(new Person() { FirstName = “Subodh”, LastName = “Pushpak”, Gender = “M”, Dept = “Development” }); peeps.Add(new Person() { FirstName = “abc”, LastName = “Singh”, Gender = “F”, Dept = “Development” }); peeps.Add(new Person() { FirstName = “Happy”, LastName = “Singh”, Gender = “F”, Dept = “Testing” }); peeps.Add(new Person() { FirstName = “Hariraj”, LastName = “Singh”, Gender = “M”, Dept = “Testing” }); return peeps; } } #region FirstName #region LastName #region Gender #region Dept |
Feel free to add your comments / suggestions.




Hi,
I was trying this code, but it does not work when I specify the column defination instead of Autogenerating the columns. do you have any idea how to make it work.
Thanks in advance.
Irfan
Pingback: 2010 in review « Subodh Pushpak's Blog