Ok let's say we have a
Parent Window bound to a
DataContext now assume we fire a
Child Window and set its data context to that of the parent window. Now the items in the child window are bound to the data context in
TwoWay mode. When the user changes something in this child window the data in the source viewmodel will be updated. But what if the user closes the window with
DialogResult == false? How to rollback the data to its original?
For now I'm binding the data in
OneWay mode and applying the changes only when the
DialogResult == true. But I guess there must be a more elegant way to do this.
In the same way that WPF can use
System.ComponentModel.INotifyPropertyChanged you can also use the interface
System.ComponentModel.IEditableObject. This interface has the following useful methods:
Prior to displaying your window, call
BeginEdit() on your datacontext. Now any changes reflect via the usual
INotifyPropertyChanged so that the parent receives updates as usual.
If the user cancels, then call
CancelEdit() at which point your viewmodel should rollback the changes. The free set of steak knives is that your parent window is informed of the rollback via
INotifyPropertyChanged thus "reverting" the parent window too.
EndEdit() which honestly isn't required as the changes are done already.
Obviously you would need to remember somehow the prior values so that you can revert any changes.
I've just read about
System.ComponentModel.IRevertibleChangeTracking which offers the methods
RejectChanges(). Though arguably this is the interface to use for accepting and rolling back changes, it's not entirely clear whether changes made in the interim should be broadcast in the WPF scenario. Perhaps someone can help me here.
Tell me more...