Domanda

When I try to set the ItemsSource of a GridView with following properties I get the expection System.ArgumentException("Value does not fall within expected range"):

Code-Behind

OnNavigatedTo(NavigationEventArgs e) {
    ...
    itemGridView.ItemsSource = GetItems(NavigationParameter); // System.ArgumentException
    ...
}

GetItems Method

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;
}

Why do I get this error? In XAML, it's works to define a CollectionViewSource and set it as a ItemsSource.

È stato utile?

Soluzione

Instead of creating and returning a new CollectionViewSource, use an existing CollectionViewSource and update the contents:

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");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top