INotifyCollectionChanged:添加项目不会出现在给定索引'0'

Tan*_*Tan 7 c# wpf

我正在制作一个可观察的课程.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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 8

你确定错误与Remove方法有关吗?错误消息和您的源代码表明它在Add方法中.尝试_list.Count - 1在构造函数中使用正确的索引NotifyCollectionChangedEventArgs:

CollectionChanged(this, new NotifyCollectionChangedEventArgs(
                                              NotifyCollectionChangedAction.Add, 
                                              orderResponse, _list.Count - 1)
                 );
Run Code Online (Sandbox Code Playgroud)

  • 我可以确认在`Remove`(!)回调中引发了这个彻底混乱的异常,并通过将正确的索引传递给`Add`回调来修复.令人困惑的是,在"添加"上没有传递任何索引(记录为[有效的事情!](http://msdn.microsoft.com/en-us/library/ms653207.aspx))也导致这种混乱异常消息. (8认同)
  • 我在实现“排序”ObservableCollection 类后遇到了这个问题。当您将一个元素添加到列表中时,它不一定会添加到列表的末尾。但是,当引发“添加”操作的集合更改事件时,WPF 期望将该元素添加到列表的末尾。我设法解决这个问题的方法是首先将元素添加到列表的末尾,然后将其移动到正确的索引。 (3认同)