1

我应该如何在 gridview 中为分组集合制作我的集合?

当我创建List<List<MyObject>>组时,我得到分组数据,每个组中的组和元素数量很多,但我没有组标题。所以我创建了具有两个字段的对象 MyGroupedObject

public String Key;
public List<MyObject> items;

所以我把它分组在对象中。但是当我将它传递给网格视图(如下所示)时,我什么都没有。没有项目,没有组,没有任何东西

 <Page.Resources>
<!--
    Collection of grouped items displayed by this page, bound to a subset
    of the complete item list because items in groups cannot be virtualized
-->
<CollectionViewSource
    x:Name="groupedItemsViewSource"
    IsSourceGrouped="true"
    />

</Page.Resources>

比在gridview中我只是将此集合绑定为ItemsSource

这个问题基于:how to create gridview from dictionary

我在原著中创造了新的原因是很多问题,所以我想把这一切都说清楚

4

2 回答 2

2

您看过分组和语义缩放示例吗?http://code.msdn.microsoft.com/windowsapps/groupedgridview-77c59e8e

您还可以查看如何在列表或网格中对项目进行分组... http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh780627.aspx

简短的解释是......你可以用两种方法之一来做......

List<Activity> Activities = new List<Activity>(); 
Activities.Add(new Activity() 
    { Name = "Activity 1", Complete = true, 
            DueDate = startDate.AddDays(4), Project = "Project 1" });
Activities.Add(new Activity() 
    { Name = "Activity 2", Complete = true, 
            DueDate = startDate.AddDays(5), Project = "Project 2" });

接下来是获取 CollectionViewSource 中的数据

var result = from act in Activities 
             group act by act.Project into grp 
             orderby grp.Key select grp;
cvsActivities.Source = result;

或者您可以使用这样的对象属性构建层次结构......

List<Project> Projects = new List<Project>();

Project newProject = new Project();
newProject.Name = "Project 1";
newProject.Activities.Add(new Activity() 
    { Name = "Activity 1", Complete = true, DueDate = startDate.AddDays(4) });
newProject.Activities.Add(new Activity() 
    { Name = "Activity 2", Complete = true, DueDate = startDate.AddDays(5) });
newProject.Activities.Add(new Activity() 
    { Name = "Activity 3", Complete = false, DueDate = startDate.AddDays(7) });
newProject = new Project();
newProject.Name = "Project 2";
newProject.Activities.Add(new Activity() 
    { Name = "Activity A", Complete = true, DueDate = startDate.AddDays(2) });
newProject.Activities.Add(new Activity() 
    { Name = "Activity B", Complete = false, DueDate = startDate.AddDays(3) });
cvsProjects.Source = Projects;

您无法绑定到简单列表并自动为您配置分组。

于 2012-08-27T12:45:09.593 回答
1

您的数据应该与IList<MyGroupObject>MyGroupObject 的定义相同

class MyGroupObject
{
    public String Key; // used for group title
    public IList<MyObject> Items;
}

那么你CollectionViewSource应该这样定义

<CollectionViewSource
    x:Name="groupedItemsViewSource"
    IsSourceGrouped="true"
    Source="{Binding GroupItems}" <!-- Property in the backing ViewModel -->
    ItemsPath="Items" <!-- Property on the MyGroupObject class -->
/>
于 2012-08-27T15:31:03.183 回答