Link to home
Start Free TrialLog in
Avatar of AIBMass
AIBMass

asked on

Do I need to raise CollectionChanged?

I have an ObservableCollection that is set in Sub New via a service call.

Public Property MyColl as ObservableCollection(of MyClass)

Public Sub New()
.....
....
MyColl = ServiceCall.Result
End Sub

I see the collection in my UI.

During processing, the service call may be repeated.

Public Sub SomeGoodReason
...
MyColl = ServiceCall.Result
End Sub

I know the collection has actually changed. Shouldn't the setting of the collection property to the result of the service call cause the Collection Changed event to fire because it's an ObservableCollection?

or does there have to be an explicit MyColl.Add (or Remove or Clear, etc)?

And if I have to fire the event myself, can you give me a VB snippet?

Thanks.
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

No it won't fire because the collection itself hasn't changed. The thing that has changed is that the MyColl variable now points to a different collection.

You can't raise the event yourself because it is a Protected method of the class. You'll either need to add/remove a dummy item, or implement INotifyPropertyChanged and raise your own event.
Avatar of AIBMass
AIBMass

ASKER

I'm sure you are correct. However, I try:

... implements INotifyCollectionChanged

Public Event CollectionChanged (sender as Object, e as NotifyCollectionChangedEventArgs) implements....

Then:

Me.MyColl = ServiceCall.Result
RaiseEvent CollectionChanged (Me.MyColl, _
    new(NotifyCOllectionChangedEventArgs(NotifyCollectionChangedAction.Reset))


and I still don't see my changed.

Did I set the event arguments correctly?
Implementing INotifyCollectionChanged probably isn't going to work if your class doesn't derive from Collection.

Instead of simply replacing your collection, it might be better to do (untested so might need tweaking):
MyColl.Clear()
MyColl.AddRange(ServiceCall.Result)

Open in new window

That way you are actually modifying the current collection, rather than replacing it, which should make the normal event mechanism play properly.
Avatar of AIBMass

ASKER

Hmmm...MyColl does derive from Collection, it's an ObservableCollection - yes?

And AddRange does not exist for an ObservableCollection.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AIBMass

ASKER

Ultimately I had to use:

Me.MyColl.Clear
For each it as MyClass in ServiceCall.Result
  Me.MyColl.Add(it)
Next