确定列表视图的折叠组

时间:2019-10-18 05:41:46

标签: c# wpf listview

是否有任何方法可以确定(如果可能,以编程方式设置)哪些组已折叠,哪些不在列表视图中。设置列表视图分组的方法如下:

CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(LvMslInfoTable.ItemsSource);
PropertyGroupDescription groupDescription = new PropertyGroupDescription("GroupObject");
view.GroupDescriptions.Add(groupDescription);
view.SortDescriptions.Add(new SortDescription("GroupObjectSortOrder", ListSortDirection.Ascending));

1 个答案:

答案 0 :(得分:0)

花了我一段时间才重新开始那个项目。 @Oleg的链接确实很有帮助,因为它指向了Expander控件。唯一缺少的是进入可视树并找到该元素。从那时起,相对容易找到缺失的部分。这是我最后使用的代码。 GetDescendantByType方法也是从Stackoverflow的此处复制的。其余的将扩展状态与组名一起存储(expandedStateStatus是包含这些条目的Dictionary)。

        StackPanel sp = (StackPanel)GetDescendantByType(LvMslInfoTable, typeof(StackPanel));
        foreach (var gi in sp.Children.Cast<GroupItem>())
        {
            var tb = (TextBlock)GetDescendantByType(gi, typeof(TextBlock));
            if (tb == null) continue;

            Expander exp = (Expander)GetDescendantByType(gi, typeof(Expander));
            if (exp == null) continue;

            if (!expandedStateStatus.ContainsKey(tb.Text))
            {
                expandedStateStatus.Add(tb.Text, exp.IsExpanded);
            }
        }



    private static Visual GetDescendantByType(Visual element, Type type)
    {
        if (element == null) return null;
        if (element.GetType() == type) return element;
        Visual foundElement = null;
        if (element is FrameworkElement frameworkElement)
        {
            frameworkElement.ApplyTemplate();
        }

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
        {
            Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
            foundElement = GetDescendantByType(visual, type);
            if (foundElement != null)
            {
                break;
            }
        }
        return foundElement;
    }