Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverting an object is a user clicks "Cancel" in WPF

Tags:

wpf

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!

like image 330
Phone Developer Avatar asked Nov 09 '11 21:11

Phone Developer


2 Answers

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...

like image 68
sll Avatar answered Sep 25 '22 09:09

sll


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.

like image 24
Emond Avatar answered Sep 24 '22 09:09

Emond