如何从分组的gridview构造数据

时间:2012-08-27 12:12:13

标签: c# xaml windows-8 windows-runtime winrt-xaml

我应该如何在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

我在原版中创造了新的原因是很多问题,所以我想把它弄清楚

2 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分: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 -->
/>