如何恢复 ObservableCollection 的更改值?
我有一个类的 ObservableCollection
。
class person
{
string name;
string age;
}
我还有一个 List
。我从填充在集合中的 XML 标签以及 XML 列表中获取数据。
listVAR.add (new person(xml.name.value,xml.age.value));
collectionVAR(new person(xml.name.value,xml.age.value));
现在我修改集合中的数据。有一种情况,我必须恢复旧值,但是当我添加它们时,首先清除集合,旧值就会反映出来。例如:
通过 XamDataGrid
将集合中的年龄从 35 更改为 45。现在我的列表的值为 35。
collectionVAR.clear();
foreach(people item in listVAR)
{
collectionVAR.add(item);
}
但在这里我看到值 35 未恢复。谁能向我解释为什么?
I have an ObservableCollection<T>
of a class.
class person
{
string name;
string age;
}
I also have one List<T>
. I'm getting data from XML tags populating in the collection as well as list from the XML.
listVAR.add (new person(xml.name.value,xml.age.value));
collectionVAR(new person(xml.name.value,xml.age.value));
Now I modify the data in collection. There is a senario where I have to restore the old values, but when I add them, clearing the collection first, the old value is reflected. For example:
age changed from 35 to 45 in collection through an XamDataGrid
. Now my list has the value 35.
collectionVAR.clear();
foreach(people item in listVAR)
{
collectionVAR.add(item);
}
but here I see that value 35 not restored. Can anyone explain to me why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是,仅存在
Person
类的一个副本,而该副本可能包含在两个集合(主集合和ObservableCollection
)中。因此,当您将集合中的项目添加到
ObservableCollection
时,它们将指向相同的对象。因此,当您编辑对象时,它们将在两个集合中发生更改。解决方案是首先克隆
Person
对象,然后将克隆添加到ObservableCollection
中。Your problem is that only one copy of the
Person
class exists while this could be contained within two collections (main collection and theObservableCollection
).So when you add items from the collection to
ObservableCollection
, they will be pointing to the same objects. So when you edit objects, they will be changed in both collections.Solution is to clone the
Person
objects first and then add the clone to theObservableCollection
.