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

后端 未结 2 1990
太阳男子
太阳男子 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 collection)
    {
        foreach (var i in collection) 
        {
            Items.Add(i);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(
                NotifyCollectionChangedAction.Add, i));
        }
    }
    

提交回复
热议问题