Search code examples
wpfmvvmprism

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?


Solution

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