The program uses a simple UserControl (modal window) in which a collection of color labels is edited.

enter image description here

The collection itself is as follows:

 public static ObservableCollection<ColorVM> Colors { get; set; } = new ObservableCollection<ColorVM>() { new ColorVM {Title = "Green", Value = "#a0db8e"}, new ColorVM {Title = "Red", Value = "#b44545"}, new ColorVM {Title = "Orange", Value = "#e28356"}, new ColorVM {Title = "Blue", Value = "#2b90f5"} }; 

I don’t understand how to implement the Cancel button method so that all changes in the collection are rolled back to the moment before the start of editing. The idea was to implement ICloneable from ColorVM and copy the entire original collection for editing in a UserControl . But I am not sure of the correctness of this approach.

Tell me, how is this implemented correctly?

  • I am for copying fields from one class to another. How - already at your discretion. You can make the interface implement, you can use pens, you can try to fasten the automatically generated code for copying fields and properties. - Monk

1 answer 1

Yes, cloning is the right approach.

When you open your object for editing, you create its clone. There are two approaches:

  1. either you give a clone for editing, and when the user chooses OK, replace the original with a clone,
  2. or you give the original for editing, and when you select Cancel, replace the edited original with a clone.

In the second approach, the remaining parts of the program see changes in the edited object right during editing, so this approach now seems to be more fashionable.


If the collection is large (say, tens or hundreds of thousands of elements), it makes sense to think about optimization. You can store not two copies of the collection, but one and a set of editing operations in the form of objects representing operations: adding an element, deleting, replacing one element with another. But this should not be bothered while the performance of the simple approach remains normal.