I have a Window that serves as a dialog in a WPF application. This dialog has an "OK" and a "Cancel" button. I am setting the DataContext of the Window to an instance of an object in my application. The user can change the values of the properties of the object within the Window. If a user clicks "Cancel", I want to revert the property values back to their original values. Is there an easy way to do this in WPF?
For instance, I know with RIA data services there is RejectChanges. Is there something similar on the client-side with WPF?
Thanks!
In object which is set to DataContext (ideally it should be ViewModel in MVVM approach) expose two commands
public ICommand CancelCommand { get; set; }
public ICommand OkCommand { get; set; }
Then for the buttons assign these commands like shown below
<Button Command="{Binding CancelCommand}" ... />
You've to keep two copies of object, a copy should be created by Deep Copy or if an object has a few editable fields you can keep those as class fields. Basically on initialization stage do backup editable object properties, then bind to DataContext
editable version of object. In Cancel Command handler - restore from a backup copy...
When the object is simple (just a few properties of basic types such as string, int, etc.) DeepCopy or IEditableObject is a very good option.
When the object is a node in a more complex hierarchy this might prove to be too difficult and going back to the server/model and reloading the original data is much easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With