可观察集合替换项目
我有一个 ObservableCollection,我可以从集合中添加和删除项目。但我无法替换集合中的现有项目。有一种方法可以替换项目并将其反映在我的绑定组件上。
System.Collections.Specialized.NotifyCollectionChangedAction.Replace
谁能告诉我如何做到这一点?
I have a ObservableCollection
, I can add and remove item from the collection. But I can't replace an existing item in the collection. There is a way to replace an item and reflect that on my bound components.
System.Collections.Specialized.NotifyCollectionChangedAction.Replace
Can anyone please show me how to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
替换可观察集合中的项目的简单扩展方法:
Simple extension method for replace item in observable collection:
更新:索引器使用重写的 SetItem 并通知更改。
我认为有关使用索引器的答案可能错误,因为问题是关于替换和通知。只是澄清一下:
ObservableCollection
使用其基Collection
类中的索引器,该类又是List的包装器;
,它是T
简单数组的包装。并且 ObservableCollection 实施。因此,当您使用索引器替换 ObservableCollection 中的项目时,它会从 Collection 类调用以下代码:
它仅检查边界并调用使用底层 List 索引器的 SetItem 类:
在赋值期间,不会调用
CollectionChanged
事件,因为底层集合对此一无所知。但是,当您使用
SetItem
方法时,它是从 ObservableCollection 类调用的:赋值后,它调用
OnCollectionChanged
方法,该方法用触发
操作参数。CollectionChanged
事件NotifyCollectionChangedAction.Replace结论:继承自 ObservableCollection 的自定义类和调用
base.SetItem()
的Replace
方法的想法值得一试。Updated: Indexer uses overridden SetItem and notifies about changes.
I think the answer about using indexer may be wrong, because the question was about replace and notify.Just to clarify:
ObservableCollection<T>
uses indexer from its baseCollection<T>
class, which in turn is a wrapper ofList<T>
, which is a wrapper of simple array ofT
. And there's no override for indexer method in ObservableCollection implementation.So when you use indexer to replace an item in ObservableCollection it invokes the following code from Collection class:
It just checks boundaries and calls SetItem that uses indexer of underlying List class:
During assignment there is no call to the
CollectionChanged
event, because underlying collections know nothing of it.But when you use
SetItem
method, it is called from ObservableCollection class:After assignment it calls
OnCollectionChanged
method, which firesCollectionChanged
event withNotifyCollectionChangedAction.Replace
action parameter.As a conclusion: the idea with custom class inherited from ObservableCollection and
Replace
method that callsbase.SetItem()
worth a try.