【问题标题】:C#: System.ArgumentException (Out of expected range)C#:System.ArgumentException(超出预期范围)
【发布时间】:2014-03-25 15:56:27
【问题描述】:

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

【问题讨论】:

标签: c# wpf xaml exception microsoft-metro


【解决方案1】:

使用现有的 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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多