当我尝试使用以下属性设置GridView的ItemsSource时,我得到了System.ArgumentException("Value does not fall within expected range")
:
代码隐藏
OnNavigatedTo(NavigationEventArgs e) {
...
itemGridView.ItemsSource = GetItems(NavigationParameter); // System.ArgumentException
...
}
GetItems方法
private CollectionViewSource GetItems(string key) {
var items = new List<Item>
{
new Item { Category = "blah", Title = "something" },
...
};
var itemsByCategories = unsortedItems.GroupBy(x => x.Category)
.Select(x => new ItemCategory { Title = x.Key, Items = x.ToList() });
var _foo = new CollectionViewSource();
_foo.Source = itemsByCategories.ToList();
_foo.IsSourceGrouped = true;
_foo.ItemsPath = new PropertyPath("Items");
return _foo;
}
为什么会出现此错误?
在XAML中,它可以定义CollectionViewSource
并将其设置为ItemsSource
。
答案 0 :(得分:0)
使用现有的CollectionViewSource并更新内容,而不是创建和返回新的CollectionViewSource:
OnNavigatedTo(NavigationEventArgs e) {
...
GetItems(itemGridView.ItemsSource, NavigationParameter);
...
}
private void GetItems(CollectionViewSource source, string key) {
var items = new List<Item>
{
new Item { Category = "blah", Title = "something" },
...
};
var itemsByCategories = unsortedItems.GroupBy(x => x.Category)
.Select(x => new ItemCategory { Title = x.Key, Items = x.ToList() });
source.Source = itemsByCategories.ToList();
source.IsSourceGrouped = true;
source.ItemsPath = new PropertyPath("Items");
}