INotifyCollectionChanged:添加的项目未出现在给定的索引"0"处 [英] INotifyCollectionChanged: Added item does not appear at given index '0'

查看:55
本文介绍了INotifyCollectionChanged:添加的项目未出现在给定的索引"0"处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上一个可观察的课.Add方法工作正常.但是然后我尝试调用Remove()方法时出现此错误:

I'm making a observable class. The Add methods works fine. But then I'm trying to call the Remove() method I get this error:

添加的项目未出现在给定的索引'0'处"

"Added item does not appear at given index '0'"

但是我将NotifyCollectionChangedAction枚举设置为Remove,如下代码.

but I'm setting the NotifyCollectionChangedAction enum to Remove as the code below.

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

推荐答案

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

Are you sure the error is with the Remove method? The error message and your source code indicate it is in the Add method. Try using the correct index _list.Count - 1 in the constructor of NotifyCollectionChangedEventArgs:

CollectionChanged(this, new NotifyCollectionChangedEventArgs(
                                              NotifyCollectionChangedAction.Add, 
                                              orderResponse, _list.Count - 1)
                 );

这篇关于INotifyCollectionChanged:添加的项目未出现在给定的索引"0"处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆