简体   繁体   中英

How can I restore the changed value of an ObservableCollection?

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?

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 ).

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 the ObservableCollection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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