替换ObservableCollection< T>中的项目时ArgumentOutOfRangeException

编程入门 行业动态 更新时间:2024-10-25 04:20:26
本文介绍了替换ObservableCollection< T>中的项目时ArgumentOutOfRangeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在研究ObservableCollection的Refresh()扩展方法,该方法基于匹配键添加,删除或替换项目(这意味着当绑定到DataGrid时,网格不会重新滚动并且项目不会更改除非将其移除,否则它们的位置).

I'm working on a Refresh() extension method for ObservableCollection which adds, removes or replaces items based on a matching key (this means when bound to a DataGrid the grid doesn't re-scroll and items don't change their position unless they were removed).

问题是当我替换ObservableCollection中的项目时,最后一个项目引发ArgumentOutOfRangeException,我在这里缺少什么?

Problem is when I replace items in the ObservableCollection the last item throws an ArgumentOutOfRangeException, what am I missing here?

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

推荐答案

您对新旧事物的理解不正确.这个:

You've got Old and New the wrong way round. This:

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

应该是这样:

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

当前,您正在寻找 new 值的索引,该索引将为-1 ...

Currently you're looking for the index of the new value, which will be -1...

更多推荐

替换ObservableCollection&lt; T&gt;中的项目时ArgumentOutOfRangeException

本文发布于:2023-11-07 06:41:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565793.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   amp   ObservableCollection   lt   ArgumentOutOfRangeException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!