Implement AddRange on ObservableCollection with proper support for DataBinding

吃可爱长大的小学妹 提交于 2019-12-04 13:01:53

It could be because your sending the NotifyCollectionChangedAction.Reset notification, maybe just the NotifyCollectionChangedAction.Add will work, Maybe :)

public class ObservableRangeCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> collection)
    {
        foreach (var i in collection)
        {
            Items.Add(i);
        }
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, collection.ToList()));
    }
}

I've used this in a project recently...

public class RangeObservableCollection<T> : ObservableCollection<T>
{
    private bool _suppressNotification = false;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (!_suppressNotification)
            base.OnCollectionChanged(e);
    }

    public void AddRange(IEnumerable<T> list)
    {
        if (list == null)
            throw new ArgumentNullException("list");

        _suppressNotification = true;

        foreach (T item in list)
        {
            Add(item);
        }
        _suppressNotification = false;
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

The problem you are experiencing with DataBinding might be connected to the fact that you don't raise PropertyChanged for indexer (property name "Item[]") as it happens in ObservableCollection according to the source code.

You can also have a look at a nice implementation of ObservableRangeCollection by James Montemagno here on GitHub, it inherits from ObservableColection and includes AddRange and ReplaceRange methods with all PropertyChaged and CollectionChanged notifications needed for DataBinding.

It took me ages, the trouble was always with the arguments to pass to the NotifyCollectionChangedEventArgs ctor. There are many different ctors that take different arguments, depending on the action. The following seems to finally work for me: https://github.com/lolluslollus/Utilz/blob/master/Utilz/SwitchableObservableCollection.cs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!