A common scenario that is required by applications is the ability to show an entity in a view mode, and when the user wishes to edit that entity, another view is loaded in edit mode.
In most cases, you would allow the user to save or cancel his changes.
To illustrate the concept, consider the following interface –
|When a user clicks ‘Edit’:|
Usually, in a MVVM application, you would have a view model for each list item on the left screenshot.
When the user clicks ‘Edit’ and the editable view is shown as modal dialog, you may want to use the same view model.
However, if it is the same instance, how would you support cancelling the save operation. Additionally, how would you prevent that changes in the edit mode won’t be reflected in the view mode until the user chooses to save the changes. (If you use bindings, the change would reflect in the view mode as well, as long as the binding is active and the source is updated).
Well, there are numerous ways to go about it.
- Use the same instance: To use the same actual instance, a common approach is to define all the bindings in the editable view with update source trigger set to ‘Explicit’.
This gives you the ability to save state explicitly when the user chooses to save his changes.
This method isn’t suitable for all the cases. If you have more than a plain simple view model where properties may set other properties or commands can be invoked from the edit view – you’re in a dead end. Plus, you can’t use the IDataErrorInfo validation model since the bindings don’t update the source nor calls its validation methods.
- Use a separate instance using some sort of cloning and merging methods: To support more advanced scenarios, or simply provide a complete solution, you would generally prefer binding the editable view to a new instance.
Obviously, you would need to construct the new instance, either imperative instantiation/cloning or use serialization which is quite a common technique in this scenario.
Finally, if the user chooses to save his changes, you would need to merge back the changes to the instance in the view mode or simply replace it with the new instance.
I plan to address both the approaches mentioned above in the next post to show some nice extensions that you can use, so stay tuned.