How can I raise a CollectionChanged event on an ObservableCollection, and pass it the changed items?

后端 未结 2 1978
太阳男子
太阳男子 2020-12-30 23:37

I have a class that inherits from ObservableCollection and adds a few additional methods such as AddRange and RemoveRange

My b

相关标签:
2条回答
  • 2020-12-31 00:15

    I've been looking into it and apparently the CollectionChanged method cannot be raised with multiple items.

    So I can call

    OnCollectionChanged(new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Add, singleItem));
    

    but I can't call

    OnCollectionChanged(new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Add, listOfItems));
    

    For now what I have done is simply raise the Add event for every item added, but I am still rather unhappy at this since it means I raise the CollectionChanged event for every item in the AddRange method instead of only once.

    public void AddRange(IEnumerable<T> collection)
    {
        foreach (var i in collection) 
        {
            Items.Add(i);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(
                NotifyCollectionChangedAction.Add, i));
        }
    }
    
    0 讨论(0)
  • 2020-12-31 00:17

    This works fine for me "stand-alone". Meaning I'm not using an ObservableCollection for data binding. So it's not an ObservableCollection issue but rather a ListCollectionView limitation.

    Please read the following article, it's a very interesting read:

    Nathan Nesbit's Blog

    0 讨论(0)
提交回复
热议问题