简体   繁体   English

如何还原ObservableCollection的更改值?

[英]How can I restore the changed value of an ObservableCollection?

I have an ObservableCollection<T> of a class. 我有一个类的ObservableCollection<T>

class person
{
   string name;
   string age;
}

I also have one List<T> . 我也有一个List<T> I'm getting data from XML tags populating in the collection as well as list from the XML. 我从集合中填充的XML标签以及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. 在一个senario中,我必须还原旧值,但是当我添加它们时,首先清除集合,就会反映旧值。 For example: 例如:

age changed from 35 to 45 in collection through an XamDataGrid . 通过XamDataGrid收集,年龄从35变为45。 Now my list has the value 35. 现在我的清单的值为35。

collectionVAR.clear();

foreach(people item in listVAR)
{
    collectionVAR.add(item);
}

but here I see that value 35 not restored. 但是在这里我看到值35没有恢复。 Can anyone explain to me why? 谁能向我解释为什么?

Your problem is that only one copy of the Person class exists while this could be contained within two collections (main collection and the ObservableCollection ). 您的问题是仅存在一个Person类的副本,而该副本却可以包含在两个集合中(main集合和ObservableCollection )。

So when you add items from the collection to ObservableCollection , they will be pointing to the same objects. 因此,当您将集合中的项目添加到ObservableCollection它们将指向相同的对象。 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 the ObservableCollection . 解决方案是先克隆Person对象,然后将克隆添加到ObservableCollection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM