Say, I have an 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)
Now, how I should implement the handler of this 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
Is it correct? What to to for the Move, Replace, Reset actions?
That is correct.
For
Replace, you should remove handlers from the old items and add them to the new items.For
Reset, you should panic, because you cannot know which items were removed or added.