DataGrid-折叠除第一个组外的所有组 [英] DataGrid - collapse all groups except the first one

查看:110
本文介绍了DataGrid-折叠除第一个组外的所有组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有分组ItemsSource的DataGrid。每个组上都有一个扩展器,因此我可以扩展/折叠所有组。现在,我尝试默认折叠所有组,但保持第一个组展开。商品来源是动态的,因此我无法建立任何转换器来检查组名。我必须按组索引进行操作。

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.

是否可以在XAML中进行操作?还是在代码后面?

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

请帮忙。

推荐答案

这可能有点晚了,但是为了帮助解决类似的问题,在这种情况下定义 Visual Tree helper class将很有帮助。

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;

功劳归功于此论坛

这篇关于DataGrid-折叠除第一个组外的所有组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆