有效地将一系列值添加到

有效地将一系列值添加到

本文介绍了有效地将一系列值添加到 ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ObservableCollection 项目绑定到我的视图中的列表控件.

I have an ObservableCollection of items that is bound to a list control in my view.

我有一种情况,我需要在集合的开头添加一大块值.Collection<T>.Insert 文档将每个插入指定为 O(n) 操作,并且每个插入还会生成一个 CollectionChanged 通知.

I have a situation where I need to add a chunk of values to the start of the collection.Collection<T>.Insert documentation specifies each insert as an O(n) operation, and each insert also generates a CollectionChanged notification.

因此,理想情况下,我希望一次插入整个项目范围,这意味着只对底层列表进行一次随机播放,并希望有一个 CollectionChanged 通知(可能是重置").

Therefore I would ideally like to insert the whole range of items in one move, meaning only one shuffle of the underlying list, and hopefully one CollectionChanged notification (presumably a "reset").

Collection<T> 没有公开任何执行此操作的方法.List 有 InsertRange(),但是 IList,Collection 通过它的 Items 属性没有.

Collection<T> does not expose any method for doing this. List<T> has InsertRange(), but IList<T>, that Collection<T> exposes via its Items property does not.

有没有办法做到这一点?

Is there any way at all to do this?

推荐答案

ObservableCollection 公开了一个受保护的 Items 属性,该属性是没有通知语义的底层集合.这意味着您可以通过继承 ObservableCollection 来构建一个可以满足您需求的集合:

The ObservableCollection exposes an protected Items property which is the underlying collection without the notification semantics. This means you can build a collection that does what you want by inheriting ObservableCollection:

class RangeEnabledObservableCollection<T> : ObservableCollection<T>
{
    public void InsertRange(IEnumerable<T> items)
    {
        this.CheckReentrancy();
        foreach(var item in items)
            this.Items.Add(item);
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

用法:

void Main()
{
    var collection = new RangeEnabledObservableCollection<int>();
    collection.CollectionChanged += (s,e) => Console.WriteLine("Collection changed");
    collection.InsertRange(Enumerable.Range(0,100));
    Console.WriteLine("Collection contains {0} items.", collection.Count);
}

这篇关于有效地将一系列值添加到 ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:16