我有一个类继承自ObservableCollection
并添加了一些其他方法,例如AddRange
和RemoveRange
我的基本方法调用是这样的:
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
我的问题是我想访问e.NewItems
或e.OldItems
在CollectionChanged
事件中对集合中的任何项目执行操作,并且该NotifyCollectionChangedAction.Reset
操作没有传递这些值
void Instances_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) // e.NewItems is always null
{
foreach (var item in e.NewItems)
{
if (item is EventInstanceModel)
((EventInstanceModel)item).ParentEvent = this;
}
}
}
所以我想我可以只使用NotifyCollectionChangedAction.Add
而不是Reset
,但是会引发Range actions are not supported
异常
public void AddRange(IEnumerable<T> collection)
{
var addedItems = collection.ToList();
foreach (var i in addedItems) Items.Add(i);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, addedItems));
}
所以我的问题是,我怎样才能引发一个 CollectionChanged 事件,并将它传递给新的或旧的项目列表?