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 fr开发者_StackOverflow中文版om 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
.
精彩评论