views:

47

answers:

2

How can I subscribe to a ObservableCollection<??> without knowing the element type of the collection? Is there a way to do this without too many 'magic strings'?

This is a question for the .NET version 3.5. I think 4.0 would make my life much easier, right?

Type type = collection.GetType();
if(type.IsGenericType 
   && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
{
    // I cannot cast the collection here
    ObservableCollection<object> x = collection;
}

Thanks for your time.

A: 

You should be able to subscribe to CollectionChanged with a little bit of reflection:

void AddCollectionChangedHandler(ICollection collection, NotifyCollectionChangedEventHandler handler)
{
    Type type = collection.GetType();
    if(type.IsGenericType
       && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
    {
        EventInfo collectionChanged = type.GetEvent("CollectionChanged");
        collectionChanged.AddEventHandler(collection, handler);
    }
}

It uses one 'magic string' but it subscribes the given handler to the event.

Garrett
+1  A: 

ObservableCollection implements INotifyCollectionChanged interface, so it can be very simple:

((INotifyCollectionChanged) collection).CollectionChanged += 
        collection_CollectionChanged;
Restuta
I should have been able to come up with this on my own!
Julian Lettner
Happy to help you, maybe +1 ? =)
Restuta