我正在制作一个可观察的课程.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)
你确定错误与Remove方法有关吗?错误消息和您的源代码表明它在Add方法中.尝试_list.Count - 1在构造函数中使用正确的索引NotifyCollectionChangedEventArgs:
CollectionChanged(this, new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add,
orderResponse, _list.Count - 1)
);
Run Code Online (Sandbox Code Playgroud)