1
說,我有一個ObservableCollection的ObservableCollection和處理程序
Class Person
Name
Event DidSomething
Class House
WithEvents People as ObservableCollection(of Person)
Sub OnPersonDidSomething(p as Person)
Console.WriteLine("{0} did something", p.Name)
現在,我應該如何實現這個的ObservableCollection的處理程序?
Private Sub People_CollectionChanged(_
sender As Object, _
e As NotifyCollectionChangedEventArgs) Handles People.CollectionChanged
Select Case e.Action
Case Specialized.NotifyCollectionChangedAction.Add
For Each mp As Person In e.NewItems
RemoveHandler mp.DidSomething, AddressOf OnPersonDidSomething
AddHandler mp.DidSomething, AddressOf OnPersonDidSomething
Next mp
Case Specialized.NotifyCollectionChangedAction.Remove
For Each mp As Person In e.NewItems
RemoveHandler mp.DidSomething, AddressOf OnPersonDidSomething
Next mp
End Select
End Sub
它正確嗎?什麼爲Move, Replace, Reset
行動?
對於重置,我應該刪除所有OldItem的處理程序,並添加一個新的實際的? – serhio 2011-12-19 17:18:38
好問題。你應該刪除並添加到新舊項目,但我相信他們將是空的。爲避免內存泄漏,您可能需要維護一個單獨的已知項目集合以從中刪除(然後添加到集合中的所有內容) – SLaks 2011-12-19 17:18:56
查看源代碼,只有在調用Clear()時纔會引發Reset,並且不會給你舊的物品。要麼不支持Clear()或者創建一個單獨的列表來跟蹤舊的項目。 – SLaks 2011-12-19 17:20:43