Windows 8 Metro应用程序CollectionViewSource数据绑定问题

4

我有一个CollectionViewSource

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

将其作为itemsSource并将其提供给GridView。
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"   

代码后台文件中设置了源代码:
groupedItemsViewSource.Source = AllGroups;

并且 AllGroups 是:
public ObservableCollection<DataGroup> AllGroups

其中DataGroup包含一个可观察的项目集合

 public ObservableCollection<DataItem> Items

问题在于它不显示带有项的组,而是只显示与AllGroups中的3个DataGroup相对应的3个GridViewItem。
我尝试添加IsSourceGrouped =“true”,但这样做会导致应用程序崩溃,出现一个窗口显示“myapp.exe [3192]中发生了未处理的Win32异常”。
2个回答

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}" ... />

我按照你的建议实现了GroupedObservableCollection,但是每当我添加issourcegrouped = true时,应用程序就会崩溃。如果我删除issourcegrouped,则可以运行,但是我仍然只能看到3个数据组的3个项目。 - user970012
你在每个DataGroup对象中设置了不同的Key属性吗?同时,AllGroups和Items都是属性,而不是字段? - Martin Suchan
both allgroups and items are properties. Key properties are fine, but allgroups is empty at the beginning, I get data from a source, and when I add the first datagroup to AllGroups this is when it crashes if I have issourcegrouped = true. I removed it, put a breakpoint, and I see AllGroups having the data just fine, but still in the UI the binding works wrong. Also when I set the groupedItemsViewSource.View as a source to the datagrid I see nothing. If I set groupedItemsViewSource alone then I get the 3 items wrong. - user970012

0

看起来你缺少的只是在CollectionViewSource上添加IsSourceGrouped="true"属性。


当我添加这个时,它会崩溃,并显示“myapp.exe [3192] 中发生未处理的 win32 异常”。 - user970012

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接