3

I'm writing a C# WPF Application using MVVM. In this application I have a window which displays a list of items, which are backed by an associated view model class. I want the user to be able to select an item from the list and click an edit button to open up the item for editing in a separate window. From the edit window the user can then click "Save" to save their changes, or "Cancel" to discard them. They will then be returned to the main window with the original list of items, which may or may not be updated.

I'm trying to come up the best way to handle the view models between the main and edit windows.

Option 1

Pass the same item view model used by main window to the editor window. Then in some way save the state of the view model before any edits. Let the editor window edit the single item view model. If the user cancels change the model back to the saved state.

This doesn't seem like the right option. I don't like the idea that the main window may be responding to INotifiedPropertyChanged events while it's in the background, and that ultimately don't matter because the user could end up canceling their edits.

Option 2

Create a clone of the view model to pass to the editor window to edit. If the user cancels the edit the clone is discarded. If the user chooses to save their changes the existing view model is removed from the main window, and replaced with the updated version.

I'm afraid replacing the view model will have other undesired effects like the user loosing their current selection when the item is replaced, or the new version always being inserted at the top of bottom of the list.

Option 3

The same as the option above but rather then replacing the existing view model with the updated version copy the values from it into the original item view model held by the main window. Then just discard the edited version returned by the editor.


Is there an option that I am missing that doesn't require writing code to clone my classes and or copy all the values from one instance to another?

Eric Anastas
  • 21,675
  • 38
  • 142
  • 236
  • Check out [IEditableObject](https://msdn.microsoft.com/en-us/library/system.componentmodel.ieditableobject.aspx), it's quite a good way to handle rolling back values on edit cancelation, not sure if it's the 'best' method though. – learningcs Jun 12 '15 at 01:55
  • Ahh thanks. Is there any feature of WPF that makes use of this like how databinding uses INotifyPropertyChanged? Or is it just up to to call the methods on the interface? – Eric Anastas Jun 12 '15 at 08:32
  • Your viewModel should have some way to initialize its fields based on some model, just recall this initializing function when you want to cancel changes ? – franssu May 12 '16 at 15:17
  • Does this answer your question? [How to cancel an edit to an object using MVVM?](https://stackoverflow.com/questions/1091036/how-to-cancel-an-edit-to-an-object-using-mvvm) – StayOnTarget May 04 '20 at 18:42

0 Answers0