NotifyCollectionChangedArgs的错误?

时间:2017-10-23 23:54:57

标签: c# wpf

我正在编写自己的可观察集合类。我的班级继承了ICollection<T>INotifyCollectionChanged

我的ICollection<T>.Remove(T item)方法如下:

public bool Remove(T item)
{            
   if (_innerCollection.Contains(item))
   {
      List<T> removes = new List<T>();
      removes.Add(item);
      _innerCollection.Remove(item);
      CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,removes));
       return true;
   }
   else
   {
      return false;
   }

}

这会抛出InvalidOperationException,“Collection Remove事件必须指定项目位置。”

根据文档here,我选择了一个有效的构造函数。

  

public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems)

     

动作:

     

类型:System.Collections.Specialized.NotifyCollectionChangedAction

     

导致该事件的动作。这可以设置为重置,添加或删除

我在内部得到它想要一个索引。调查构造函数in the reference source表明内部/私有构造函数使用此公共构造函数将-1替换为索引。这应该足以满足我的用例。但是,如果我知道它为什么失败了。有什么想法吗?

编辑:堆栈跟踪在此处结束:

  

MS.Internal.Data.EnumerableCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)

在参考文档here中,我明显看到抛出异常的位置。但我公开使用那个构造函数来驱逐悬崖是不公平的。

1 个答案:

答案 0 :(得分:2)

问题来自于CollectionViewSource.GetDefaultView(instanceOfYourCustomCollection)或代码中某处的简单{Binding InstanceOfMyCustomCollection}。在您的集合上创建CollectionView或者实际上只是绑定它(它将在内部创建CollectionView)时,您需要传递已删除项目的索引,因为{{1}正如你所注意到的那样,期望它会失败,否则就会失败。

我同意文件没有说清楚。