简体   繁体   中英

How do I back up the observable collection used by a WPF datagrid?

I would like to back up the observable collection used by a WPF datagrid for the purposes of a rollback/undo button to the point of the last commit. I have a refresh option that will read from the database but that will include changes from other sources. There are other similar instances of this question around, but nothing that stood out as a solution.

I have tried copying the observable collection to a list, but any changes made to the OC are also persisted to that list. But aside from a single simple assignment statement that list is not in any other way connected to the observable collection. Its almost as if the address of the observable collection was assigned to be the address of the backup list in the manner of how it is behaving. How do I overcome this?

Converting an ObservableCollection<T> to List<T> simply changes the type of collection that holds your items. The elements inside the collection remain unchanged. What you're looking to do is cloning your list. To do this your element class will have to implement the ICloneable interface. See how to implement the IClonable interface here . Once that's in place, all you have to do is call:

var clone = myObservableCollection.Select(i => (MyType)i.Clone()).ToList();

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