我正试图在集合中的对象上挂钩事件INotifyPropertyChanged
。观察PropertyChanged集合中的项目
,我见过这个问题每一个答案,说按如下方式处理:
void NotifyingItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.NewItems != null)
{
foreach(INotifyPropertyChanged item in e.NewItems)
{
item.PropertyChanged += new PropertyChangedEventHandler(CollectionItemChanged);
}
}
if(e.OldItems != null)
{
foreach(ValidationMessageCollection item in e.OldItems)
{
item.PropertyChanged -= CollectionItemChanged;
}
}
}
我的问题是当一个开发商呼吁NotifyingItems收集Clear()
,这完全失败。当发生这种情况时,这个事件处理程序调用e.Action == Reset
和e.NewItems
和e.OldItems
等于null
(我期望后者包含所有项目)。
问题是那些物品不会消失,它们不会被破坏,它们不再被当前课程监控 - 但是因为我从来没有机会取消它们的PropertyChangedEventHandler
- 他们保留即使它们已从我的NotifyingItems列表中清除,也会调用我的CollectionItemChanged
处理程序。这种情况应该如何用这种“完善的”模式来处理?
[清除ObservableCollection时,e.OldItems中没有项目]的可能重复(http://stackoverflow.com/questions/224155/when-clearing-an-observablecollection-there-are-no-items- in-e-olditems) – Rachel 2012-02-22 16:58:32