有效地将一系列值添加到 ObservableCollection
我有一个 ObservableCollection
项目,它绑定到我视图中的列表控件。
我遇到一种情况,我需要将一大块值添加到集合的开头。 Collection
文档将每个插入指定为 O(n) 操作,并且每个插入还会生成一个 CollectionChanged
通知。
因此,理想情况下,我希望一次性插入整个项目范围,这意味着只需对基础列表进行一次洗牌,并希望有一个 CollectionChanged
通知(大概是“重置”)。
Collection
不会公开任何执行此操作的方法。 List
有 InsertRange()
,但 IList
,Collection
通过以下方式公开它的 Items
属性没有。
有什么办法可以做到这一点吗?
I have an ObservableCollection
of items that is bound to a list control in my view.
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.
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>
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
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:Usage:
为了使上述答案有用而无需使用反射派生新的基类,下面是一个示例:
To make the above answer useful w/o deriving a new base class using reflection, here's an example:
这个答案没有向我显示DataGrid中的新条目。这个 OnCollectionChanged 对我有用:
This answer didn't show me the new entries in a DataGrid. This OnCollectionChanged works for me:
10 年后,现在我必须在项目中使用 C#,并且我不希望触发多个
OnCollectionChanged
。我已将 @outbred 的答案修改为扩展类。用法:
ObservableCollectionExtensions.cs
:10 years later, now that I've to use C# in my project and I don't wish to trigger multiple
OnCollectionChanged
. I've revised @outbred's answer into an Extension class.Usage:
The
ObservableCollectionExtensions.cs
:例子:
所需步数 0,10,20,30,40,50,60,70,80,90,100
-->最小值=0,最大值=100,步数=11
Example:
Desired steps 0,10,20,30,40,50,60,70,80,90,100
--> min=0, max=100, steps=11