【发布时间】:2011-08-18 12:55:45
【问题描述】:
我正在制作一个可观察的课程。 Add 方法工作正常。但后来我尝试调用 Remove() 方法时出现此错误:
“添加的项目没有出现在给定的索引'0'”
但我将 NotifyCollectionChangedAction 枚举设置为 Remove,如下所示。
public class ObservableOrderResponseQueue : INotifyCollectionChanged, IEnumerable<OrderResponse>
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
private List<OrderResponse> _list = new List<OrderResponse>();
public void Add(OrderResponse orderResponse)
{
this._list.Add(orderResponse);
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, orderResponse, 0));
}
}
public void RemoveAt(int index)
{
OrderResponse order = this._list[index];
this._list.RemoveAt(index);
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, order, index));
}
}
public void Remove(OrderResponse orderResponse)
{
var item = _list.Where(o => o.OrderDetail.TrayCode == orderResponse.OrderDetail.TrayCode).FirstOrDefault();
int index = _list.IndexOf(item);
this._list.RemoveAt(index);
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
}
}
【问题讨论】:
-
哪一行引发了异常?
-
你应该创建一个方法来一次添加或删除一组对象。
-
我也遇到了这个错误。最后将其归结为我正在添加的对象上的覆盖 Equals 和 public static bool operator == 中的一个错误。花了几个小时来调试这个,所以希望可以节省其他人一些时间。
-
如果此集合数据绑定到 UI 元素,请检查该集合是否正在非 UI 线程上更新(在您的情况下,是在调用
Remove时)。