Why is ReadOnlyObservableCollection.CollectionChanged not public?

后端 未结 8 2124
心在旅途
心在旅途 2021-01-31 06:50

Why is ReadOnlyObservableCollection.CollectionChanged protected and not public (as the corresponding ObservableCollection.CollectionChanged is)?

What is the use of a col

8条回答
  •  遇见更好的自我
    2021-01-31 07:24

    This was top hit on google so I figured I'd add my solution in case other people look this up.

    Using the information above (about needing to cast to INotifyCollectionChanged), I made two extension methods to register and unregister.

    My Solution - Extension Methods

    public static void RegisterCollectionChanged(this INotifyCollectionChanged collection, NotifyCollectionChangedEventHandler handler)
    {
        collection.CollectionChanged += handler;
    }
    
    public static void UnregisterCollectionChanged(this INotifyCollectionChanged collection, NotifyCollectionChangedEventHandler handler)
    {
        collection.CollectionChanged -= handler;
    }
    

    Example

    IThing.cs

    public interface IThing
    {
        string Name { get; }
        ReadOnlyObservableCollection Values { get; }
    }
    

    Using the Extension Methods

    public void AddThing(IThing thing)
    {
        //...
        thing.Values.RegisterCollectionChanged(this.HandleThingCollectionChanged);
    }
    
    public void RemoveThing(IThing thing)
    {
        //...
        thing.Values.UnregisterCollectionChanged(this.HandleThingCollectionChanged);
    }
    

    OP's Solution

    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;
    }
    

    Alternative 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;
    }
    

提交回复
热议问题