集合更改事件
当我们从集合中添加、删除或更新项目时,ObservableCollection
提供 CollectionChanged
事件,但它会引发单个项目更改的事件,例如,每当我添加新项目时项目到集合它引发集合。
现在,我想要的是在完成对集合的所有修改后引发事件,例如,我需要添加 2 项、删除 1 项和更新 2 项。 CollectionChanged
事件应该仅在完成所有这些添加、删除和更新后触发。
或者,假设我有一个包含所有修改的新集合,现在,我想在分配新集合时引发CollectionChanged
,例如:
ObservableCollection<string> mainCollection; //assume it has some items
mainCollection = updatedCollection; // at this point I want to raise the event.
请提供您的宝贵建议。
问候,
巴维克
ObservableCollection
provides the CollectionChanged
event whenevet we add, remove or update the item from the colleciton, but it raises the event for individual item change, for example, whenever I add the new item to the collection it raises the collection.
Now, what I want is to raise the event after completing all the modifications to the collection, for example, I need to add 2 items, delete one item and update 2 items. The CollectionChanged
event should only fire after completiong all these add, delete and update.
Or, suppose I have a new collection with all the modifications, now , i want to raise the CollectionChanged
when I assign the new collection, for example:
ObservableCollection<string> mainCollection; //assume it has some items
mainCollection = updatedCollection; // at this point I want to raise the event.
Please provide your valuable suggestions.
Regards,
BHavik
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您宁愿观看对 mainCollection 变量的赋值,而不是观察触发 ObservableCollection 类的事件。像这样的事情:
Looks like you'd rather be watching assignment to the mainCollection variable rather than the events that fire off the ObservableCollection class. Something like this:
它不会按照您编写的方式工作,原因是您已经订阅了 mainCollection 对象的事件,然后将其替换为整个另一个对象,只是通过相同的变量名称引用它。您不需要分配集合,而是将更新集合的所有元素添加到主集合
编辑:
ObservableCollection 的 AddRange:
取自这个问题
It won't work the way you written, the cause is that you've subscribed to event of mainCollection object and then replace it with whole another object just referencng it by the same variable name. You need not to assign collection but to add all elements of updated collection to main collection
EDIT:
AddRange for ObservableCollection:
Taken from this question
标准
ObservableCollection
不支持此场景。您可以使用所需的逻辑创建一个实现 INotifyCollectionChanged 接口的类,例如,使用单个方法将所有项目替换为另一个集合。这可能对 UI 不利,例如,如果选择了集合绑定元素或聚焦了该元素,则如果您完全重新初始化集合,则此状态将丢失。取决于你的场景。
Standard
ObservableCollection<T>
doesn't support this scenario. You can create a class implementingINotifyCollectionChanged
interface with the logic you need, for example, with a single method to substitute all items with another collection.That might not be good for UI, for example, if a collection-bound element was selected or focused this state will be lost if you completely re-initialize the collection. Depends on your scenario.