如何更新 ObservableCollection 类中的单个项目? [英] How do I update a single item in an ObservableCollection class?
问题描述
如何更新 ObservableCollection 类中的单个项目?
How do I update a single item in an ObservableCollection class?
我知道如何添加.而且我知道如何在for"循环中一次搜索 ObservableCollection 一个项目(使用 Count 作为项目数量的表示),但我如何更改现有项目.如果我执行foreach"并找到需要更新的项目,如何将其放回 ObservableCollection>
I know how to do an Add. And I know how to search the ObservableCollection one item at a time in a "for" loop (using Count as a representation of the amout of items) but how do I chage an existing item. If I do a "foreach" and find which item needs updating, how to I put that back into the ObservableCollection>
推荐答案
您不需要删除项目,更改,然后添加.您可以简单地使用 LINQ FirstOrDefault
方法使用适当的谓词查找必要的项目并更改其属性,例如:
You don't need to remove item, change, then add. You can simply use LINQ FirstOrDefault
method to find necessary item using appropriate predicate and change it properties, e.g.:
var item = list.FirstOrDefault(i => i.Name == "John");
if (item != null)
{
item.LastName = "Smith";
}
删除或添加项目到 ObservableCollection
将生成 CollectionChanged
事件.
Removing or adding item to ObservableCollection
will generate CollectionChanged
event.
这篇关于如何更新 ObservableCollection 类中的单个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!