Returning an object is a click of the user "Cancel" in WPF

I have a window that serves as a dialog in a WPF application. There is an OK and Cancel button in this dialog box. I set the DataContext of the window to an object instance in my application. The user can change the properties of the object in the window. If the user clicks Cancel, I want to return the property values ​​to their original values. Is there an easy way to do this in WPF?

For example, I know that there are RejectChanges in RIA data services. Is there something similar on client side with WPF?

Thanks!

+6
source share
2 answers

In the object that is set in the DataContext (ideally, it should be a ViewModel in the MVVM approach), output two commands

public ICommand CancelCommand { get; set; } public ICommand OkCommand { get; set; } 

Then, these commands are assigned to the buttons, as shown below.

 <Button Command="{Binding CancelCommand}" ... /> 

You must save two copies of the object, a copy must be created by Deep Copy, or if the object has several editable fields, you can save them as a field class. Basically, at the initialization stage, make backup copies of the properties of the object, and then bind to the DataContext editable version of the object. In the command cancel handler, restore from backup ...

+2
source

When an object is simple (just a few properties of the basic types, such as string, int, etc.), DeepCopy or IEditableObject is a very good option.

When an object is a node in a more complex hierarchy, it can be too complex and returning to the server / model and reloading the original data is much easier.

+1
source

Source: https://habr.com/ru/post/901155/


All Articles