DataGrid - 折叠除第一个组之外的所有组

时间:2011-10-06 10:43:35

标签: wpf datagrid collapse expand

我有一个带有分组ItemsSource的DataGrid。每个组都有一个扩展器,因此我可以展开/折叠所有组。现在,我正在尝试默认折叠所有组,但保留第一组扩展。项目源是动态的,因此我无法构建任何转换器来检查组名称。我必须按组索引来做。

是否可以在XAML中进行?或者在代码隐藏中?

请帮助。

3 个答案:

答案 0 :(得分:7)

这可能有点晚了,但为了解决类似的问题,在这种情况下定义“Visual tree helper class”会有所帮助。

    // 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;

信用额转到this forum

答案 1 :(得分:1)

我能够在我的ViewModel中解决这个问题 Expander在DataGrids GroupStyle的模板中定义。绑定必须是TwoWay但是显式触发,因此单击View不会更新ViewModel。谢谢Rachel

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

然后我可以在我的ViewModel中设置属性AreAllGroupsExpanded

答案 2 :(得分:0)

我不相信它可以在XAML中完成,但它可以在代码隐藏中完成。这是我在Silverlight中测试的一个解决方案。它应该在WPF中也可以正常工作。

// If you don't have a direct reference to the grid's ItemsSource, 
// then cast the grid's ItemSource to the type of the source.  
// In this example, I used a PagedCollectionView for the source.
PagedCollectionView pcv = (PagedCollectionView)myDataGrid.ItemsSource;

// Using the PagedCollectionView, I can get a reference to the first group. 
CollectionViewGroup firstGroup = (CollectionViewGroup)pcv.Groups[0];

// First collapse all groups (if they aren't already collapsed).
foreach (CollectionViewGroup group in pcv.Groups)
{
    myDataGrid.ScrollIntoView(group, null);  // This line is a workaround for a problem with collapsing groups when they aren't visible.
    myDataGrid.CollapseRowGroup(group, true);
}

// Now expand only the first group.  
// If using multiple levels of grouping, setting 2nd parameter to "true" will expand all subgroups under the first group.
myDataGrid.ExpandRowGroup(firstGroup, false);

// Scroll to the top, ready for the user to see!
myDataGrid.ScrollIntoView(firstGroup, null);