Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGrid - collapse all groups except the first one

I have a DataGrid with grouped ItemsSource. There are an expander on each group, so I can expand/collapse all the groups. Now, I'm trying to collapse all groups by default, but leave the first group expanded. The items source is dynamic, so I can't build any converter to check the group name. I must do it by group index.

Is it possible to do in in XAML? Or in code-behind?

Please, help.

like image 821
Paul Reichedt Avatar asked Oct 06 '11 10:10

Paul Reichedt


2 Answers

This might be a little late, but in order to help with similar problems, defining a "Visual tree helper class" would be helpful in this case.

    // the visual tree helper class
public static class VisualTreeHelper
{
    public static Collection<T> GetVisualChildren<T>(DependencyObject current) where T : DependencyObject
    {
        if (current == null)
            return null;

        var children = new Collection<T>();
        GetVisualChildren(current, children);
        return children;
    }
    private static void GetVisualChildren<T>(DependencyObject current, Collection<T> children) where T : DependencyObject
    {
        if (current != null)
        {
            if (current.GetType() == typeof(T))
                children.Add((T)current);

            for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(current); i++)
            {
                GetVisualChildren(System.Windows.Media.VisualTreeHelper.GetChild(current, i), children);
            }
        }
    }
}

// then you can use the above class like this:
Collection<Expander> collection = VisualTreeHelper.GetVisualChildren<Expander>(dataGrid1);

    foreach (Expander expander in collection)
        expander.IsExpanded = false;

collection[0].IsExpanded = true;

the credit goes to this forum

like image 152
Bahman_Aries Avatar answered Nov 19 '22 18:11

Bahman_Aries


I was able to solve this in my ViewModel.
The Expander is defined in the template of the DataGrids GroupStyle. The Binding must be TwoWay but triggered explicitly, so clicking in the View does not update the ViewModel. Thanks Rachel.

<Expander IsExpanded="{Binding DataContext.AreAllGroupsExpanded, RelativeSource={RelativeSource AncestorType={x:Type local:MyControl}}, UpdateSourceTrigger=Explicit}">
    ...
</Expander>

Then I can just set the property AreAllGroupsExpanded in my ViewModel.

like image 32
Heiner Avatar answered Nov 19 '22 18:11

Heiner