यह Google पर शीर्ष हिट था, इसलिए मुझे लगा कि अन्य लोगों द्वारा इसे देखने की स्थिति में मैं अपना समाधान जोड़ूंगा।
उपरोक्त जानकारी का उपयोग करके ( INotifyCollectionChanged को कास्ट करने की आवश्यकता के बारे में ), मैंने पंजीकरण करने और अपंजीकृत करने के लिए दो विस्तार विधियाँ बनाईं।
मेरा समाधान - विस्तार विधियाँ
public static void RegisterCollectionChanged(this INotifyCollectionChanged collection, NotifyCollectionChangedEventHandler handler)
{
collection.CollectionChanged += handler;
}
public static void UnregisterCollectionChanged(this INotifyCollectionChanged collection, NotifyCollectionChangedEventHandler handler)
{
collection.CollectionChanged -= handler;
}
उदाहरण
IThing.cs
public interface IThing
{
string Name { get; }
ReadOnlyObservableCollection<int> Values { get; }
}
एक्सटेंशन के तरीकों का उपयोग करना
public void AddThing(IThing thing)
{
thing.Values.RegisterCollectionChanged(this.HandleThingCollectionChanged);
}
public void RemoveThing(IThing thing)
{
thing.Values.UnregisterCollectionChanged(this.HandleThingCollectionChanged);
}
ओपी का समाधान
public void AddThing(IThing thing)
{
INotifyCollectionChanged thingCollection = thing.Values;
thingCollection.CollectionChanged += this.HandleThingCollectionChanged;
}
public void RemoveThing(IThing thing)
{
INotifyCollectionChanged thingCollection = thing.Values;
thingCollection.CollectionChanged -= this.HandleThingCollectionChanged;
}
वैकल्पिक 2
public void AddThing(IThing thing)
{
(thing.Values as INotifyCollectionChanged).CollectionChanged += this.HandleThingCollectionChanged;
}
public void RemoveThing(IThing thing)
{
(thing.Values as INotifyCollectionChanged).CollectionChanged -= this.HandleThingCollectionChanged;
}