C#:System.ArgumentException(超出预期范围)

时间:2014-03-25 15:56:27

标签: c# wpf xaml exception microsoft-metro

当我尝试使用以下属性设置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

1 个答案:

答案 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");
}