DataGrid: Programmatic Grouping Expand/Collapse

Jan 15, 2009 at 7:48 PM
Hi,

I am using an expander as my DataGrid <GroupStyle.ContainerStyle> to provide data grouping.  Once the grouping is applied, I need to provide a way to programmatically expand/collapse all groups.

What I have so far is the following, which gives me a collection of GroupItems in my Data Grid.  But from there, how do I get the Expander widget?

Am I on the right track, or way off base?

Thanks for the help,
E.

        private void toggleAllGroups(bool isExpanded) {
            CollectionView myView;
            myView = (CollectionView)CollectionViewSource.GetDefaultView(myDataGrid.ItemsSource);
            if (myView.CanGroup == true) {
                // get all currently applied groups
                ReadOnlyObservableCollection<object> groups = myView.Groups;
                foreach (object o in groups) {
                    CollectionViewGroup g = o as CollectionViewGroup;
                    DependencyObject container = PBDataGrid.ItemContainerGenerator.ContainerFromItem(g);
                    if (container != null) {
                        GroupItem gi = container as GroupItem;
                        // TODO From the GroupItem, how do I get the Expander at this point, to call IsExpanded=true/false?
                    }
                }
            }
        }

My container style definition is as follows:
    <!-- a grouping style that uses an expander to render the grouped data -->
    <Style x:Key="GroupContainerStyle"  TargetType="{x:Type GroupItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type GroupItem}">
                    <Expander IsExpanded="False" x:Name="groupExpander">
                        <Expander.Header>
                            <Grid>...........

Jan 16, 2009 at 12:22 PM
Hi,

This is the classic problem of how to locate the element you require in the visual tree. I always use a combination of Mole and the VisuaTreeHelper methods for walking the tree. See for example this blog post:

http://wpfadventures.wordpress.com/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row/

Regards,
Colin E.


Jan 16, 2009 at 7:13 PM
Fantastic - thanks very much!

From my above code, all I needed was to go one child down, and I had my Expander:
        DependencyObject dep = VisualTreeHelper.GetChild(gi, 0);

This solves my problem; but is this truly a recommended way of getting at things, in essence, circumventing the API (or in this instance, lack thereof)?

Best,
E.