windows 8 metro app collectionviewsource数据绑定问题

时间:2012-09-24 22:08:23

标签: data-binding gridview windows-8 windows-runtime winrt-xaml

我有一个collectionviewsource

<CollectionViewSource x:Name="groupedItemsViewSource" 
                          ItemsPath="Items" />

并将其作为itemssource提供给gridview

ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"   

源代码在文件后面的代码中设置:

groupedItemsViewSource.Source = AllGroups;

和AllGroups是

public ObservableCollection<DataGroup> AllGroups

其中DataGroup包含Observable项集合

 public ObservableCollection<DataItem> Items

问题是它不显示带有项目的组,而是我只获得3个gridviewitems,它们对应于AllGroups中的3个数据组

我尝试添加IsSourceGroupped =“true”但是当我这样做应用程序崩溃时,会出现一个窗口,显示“myapp.exe中出现未处理的win32异常[3192]”

2 个答案:

答案 0 :(得分:0)

CollectionViewSource中的Source属性应该实现IGrouping接口,否则这些组将无法在GridView或ListView中工作。
使用Linq表达式GroupBy将结果分组到具有指定键的组中,或者您可以像这样扩展ObservableCollection类:

public class GroupedObservableCollection<T> : ObservableCollection<T>, IGrouping<string, T>
{
    /// <summary>
    /// Key as the Group identificator.
    /// </summary>
    public string Key { get; set; }
}

并在你的类中使用它(我在ViewModel中有CollectionViewSource,而不是在XAML中):

public GroupedObservableCollection<DataItem> Items

groupedItemsViewSource = new CollectionViewSource { Source = AllGroups, ItemsPath = new PropertyPath("Items"), IsSourceGrouped = true };

这样绑定就可以了。还要确保在ListView和GridView中使用正确的绑定:

<!-- zoomed in view -->
<GridView ItemsSource="{Binding groupedItemsViewSource.View}" ... />

<!-- zoomed out view -->
<GridView ItemsSource="{Binding groupedItemsViewSource.View.CollectionGroups}" ... />

答案 1 :(得分:0)

看起来你缺少的是CollectionViewSource上的IsSourceGrouped =“true”属性。