Reputation: 7424
Basically I had created my application entirely using code behind and now I'm migrating over to MVVM. One of the challenges that I'm facing is how to deal with ViewModels that are being persisted in memory.
For example in the first version of my app I knew once the user hit the back button on a certain page that the view would be discarded and that everything would be cleared, but when I started using the ViewModel and navigated to the page it was using the ViewModel that was created the previous time I navigated to the page (In other words the constructor wasn't called).
Now is this the way it's supposed to work? I would prefer that I recreate the ViewModel everytime I navigate forward and discard it everytime I hit back. But like I said this is new to me. Am I supposed to use the same viewmodel and somehow refresh the values so it doesn't show old data?
Upvotes: 1
Views: 1498
Reputation: 4268
Here's how I clear the view model when the user leaves the page (this code is in the page's xaml.cs) file:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back)
ViewModelLocator.ClearDetailsViewModel();
base.OnNavigatingFrom(e);
}
the implementation of ClearDetailsViewModel is like
if (_detailsViewModelStatic == null) return;
_detailsViewModelStatic.Cleanup();
_detailsViewModelStatic = null;
Upvotes: 1