Subscribing to a ObservableCollection via reflection
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(ObservableCollectio开发者_如何学Cn<>))
{
// I cannot cast the collection here
ObservableCollection<object> x = collection;
}
Thanks for your time.
ObservableCollection implements INotifyCollectionChanged interface, so it can be very simple:
((INotifyCollectionChanged) collection).CollectionChanged +=
collection_CollectionChanged;
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.
精彩评论