当替换ObservableCollection<T>中的项目时出现ArgumentOutOfRangeException错误

3

我正在为ObservableCollection编写Refresh()扩展方法,它根据匹配的键添加、删除或替换项目(这意味着当绑定到DataGrid时,网格不会重新滚动,除非它们被删除,否则项目不会改变位置)。

问题是当我替换ObservableCollection中的项时,最后一项会抛出ArgumentOutOfRangeException异常,我错过了什么?

public static void Refresh<TItem, TKey>(this ObservableCollection<TItem> target, IEnumerable<TItem> source, Func<TItem, TKey> keySelector)
{
    var sourceDictionary = source.ToDictionary(keySelector);
    var targetDictionary = target.ToDictionary(keySelector);

    var newItems = sourceDictionary.Keys.Except(targetDictionary.Keys).Select(k => sourceDictionary[k]).ToList();
    var removedItems = targetDictionary.Keys.Except(sourceDictionary.Keys).Select(k => targetDictionary[k]).ToList();
    var updatedItems = (from eachKey in targetDictionary.Keys.Intersect(sourceDictionary.Keys)
                        select new
                        {
                            Old = targetDictionary[eachKey],
                            New = sourceDictionary[eachKey]
                        }).ToList();

    foreach (var updatedItem in updatedItems)
    {
        int index = target.IndexOf(updatedItem.Old);
        target[index] = updatedItem.New; // ArgumentOutOfRangeException is thrown here
    }

    foreach (var removedItem in removedItems)
    {
        target.Remove(removedItem);
    }

    foreach (var newItem in newItems)
    {
        target.Add(newItem);
    }
}
1个回答

2
您把「旧」和「新」搞反了。应该是这样的:
var updatedItems = (from eachKey in targetDictionary.Keys
                                              .Intersect(sourceDictionary.Keys)
                    select new
                    {
                        Old = targetDictionary[eachKey],
                        New = sourceDictionary[eachKey]
                    }).ToList();

should be this:

var updatedItems = (from eachKey in targetDictionary.Keys
                                              .Intersect(sourceDictionary.Keys)
                    select new
                    {
                        New = targetDictionary[eachKey],
                        Old = sourceDictionary[eachKey]
                    }).ToList();

目前你正在寻找值的索引,它将是-1...


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