stackovrflo
stackovrflo

Reputation: 93

How to reset a viewmodel in mvvm

How can I reset my viewmodel when the user clicks new button on the view that has the viewmodel as it's datacontext?

For example:

If I have a view NewCustomer and upon save, the data is saved to the DB and the newly created account number is displayed. But when the user clicks the New button in the screen, I want the view (viewmodel) to be reinitialized. Or if the user clicked cancel in the screen to clear all changes.

How can I achieve this? I am using Prism 5.0 and Unity as my container.

If I used IRegionMemberLifetime, I can clear the viewmodel data when I navigate away and navigate again to the view (by setting the KeepAlive as false on clicking New button before navigating away). But I want the form to be cleared without navigating. Can this be done?

Upvotes: 3

Views: 7506

Answers (3)

M Azam Khan
M Azam Khan

Reputation: 380

In my case

yourViewName.variableName.postValue("")

Upvotes: 0

Troels Larsen
Troels Larsen

Reputation: 4631

You could have a screen/workspaceViewModel, and another ViewModel wrapping your data.

So two classes: CarScreenViewModel and CarViewModel.

The CarScreenViewModel would have a property, say CurrentCar, which reflects what is currently selected in the screen. Then, when clicking the Create button, you simply set:

 CurrentCar = new CarViewModel();

Resetting partially loaded data will only lead to behaviour that is hard to reproduce. It is better to start with a fresh instance.

Upvotes: 4

Krishna
Krishna

Reputation: 1996

Your standard approach will be something like below

ViewModels

CustomersContainerViewModel which contains

a collection of CustomerViewModel s and ICommands like

CreateNewCustomer
DeleteExistingCustomer
UpdateExistingCustomer

Your View will contain the CustomersContainerView which will contain a collection of Customer Objects in your required UI element a button to Create new customer (which will launch a new screen which contains the newCustomer fields it can also contain cancel, which will just close the form) a button to delete (can also be a ContextMenu) a button to update (can also be a ContextMenu) which will launch a customer form filled with details from DB.

Hopefully this makes some sense... Let me know if you have problem with any of the above

Update - Forgot to add. NewCustomer Command will add a new Customer object to your CustomerCollection and that should open a NewCustomer form (or whatever you chose) for user to input the customer details. Cancel/Delete will just remove that record from the collection. Delete will update the DB as well in addition

Upvotes: 1

Related Questions