問題描述
我有一個 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!