ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

前端 未结 12 1452
走了就别回头了
走了就别回头了 2020-11-22 16:19

I want to be able to add a range and get updated for the entire bulk.

I also want to be able to cancel the action before it\'s done (i.e. collection changing besides

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 16:42

    ObservableRangeCollection should pass a test like

    [Test]
    public void TestAddRangeWhileBoundToListCollectionView()
    {
        int collectionChangedEventsCounter = 0;
        int propertyChangedEventsCounter = 0;
        var collection = new ObservableRangeCollection();
    
        collection.CollectionChanged += (sender, e) => { collectionChangedEventsCounter++; };
        (collection as INotifyPropertyChanged).PropertyChanged += (sender, e) => { propertyChangedEventsCounter++; };
    
        var list = new ListCollectionView(collection);
    
        collection.AddRange(new[] { new object(), new object(), new object(), new object() });
    
        Assert.AreEqual(4, collection.Count);
        Assert.AreEqual(1, collectionChangedEventsCounter);
        Assert.AreEqual(2, propertyChangedEventsCounter);
    }
    
    
    

    otherwise we get

    System.NotSupportedException : Range actions are not supported.
    

    while using with a control.

    I do not see an ideal solution, but NotifyCollectionChangedAction.Reset instead of Add/Remove partially solve the problem. See http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx as was mentioned by net_prog

    提交回复
    热议问题