I have a fairly standard requirement — I need to be able to open a dialog where user can change values in data-bound fields, and then choose to click OK or Cancel, where clicking Cancel reverts the changes.
I’ve looked at IEditableCollectionView, IEditableObject and BindingGroups, but they all seem to be meant for editing a single item at a time. My program provides a collection of objects in a list, user selects an item from the list and edits it using SelectedItem-bound TextBoxes. Meaning that any number of items may be edited, including adding and removing them from the list, and all of those changes need to be reverted if he presses cancel.
At first I was simply making object backups through deep-copy (serialization) and restoring them on cancel, but now the objects must contain references to other, shared objects, making this approach problematic.
What’s the best way to approach such a scenario without manually copying objects and/or values back and forth?
After more thought on the matter, I have concluded that the best way, at least for small-scale implementation, is to write a “by value deep copy” method that copies values of objects fields and properties without replacing the objects themselves (so that any references to the edited objects remain intact even when data is restored).
For this purpose I have written the following extension method:
It’s no silver bullet: it only works on objects of the same type, list items have to have a parametrless constructor and there is no way to control recursion depth. In addition, I haven’t yet had a chance to test in any long-term or more complex scenarios, but so far it does what it should (copies values between objects) and can be used for a simple backup/restore scenario: