-1

I want to observe changes in Icollection object given that I can't changed type of the object to observablecollection.How can it be achieved?

mycollectionobserver = Observable.FromEventPattern<NotifyCollectionChangedEventArgs>  (source.IcollectionItems, "CollectionChanged").Subscribe(OnItemsChanged);
veerendra gupta
  • 625
  • 1
  • 8
  • 17
  • I did it using typecasting: mycollectionobserver = Observable.FromEventPattern (source.IcollectionItems **as INotifyCollectionChanged**, "CollectionChanged").Subscribe(OnItemsChanged); – veerendra gupta Feb 19 '15 at 11:04
  • 2
    `ICollection` does not implement `INotifyCollectionChanged` so as soon as you cast it using `as` you get `null`. Peter's answer is quite correct - you need to implement a wrapper class, but since you can't change the type then you're out of luck. – Enigmativity Feb 20 '15 at 05:21

1 Answers1

2

What code is actually modifying the collection? Are you able to pass your own object reference to that code instead of the reference to the original ICollection<T> object?

If the answer to that second question is "no", then you are out of luck. But if you can replace the object reference with your own, then you can implement a wrapper around the ICollection<T> object that itself implements INotifyCollectionChanged. In that way, your own object would be able to see every modification to the collection and raise the appropriate INotifyCollectionChanged events.

If you cannot do that, then the code modifying the collection has no way to use your custom implementation, and will always be able to modify the collection without your own code having a way to know about it.

Finally, note that someone may already have written such a wrapper. I didn't find anything with a quick Google search, but I didn't try very hard. I wouldn't be surprised if one does exist.

Peter Duniho
  • 62,751
  • 5
  • 84
  • 120