How do you refresh your ViewModel when navigating back using MVVM

3k Views Asked by At

When navigating back using the back button on the phone how can I refresh my ViewModel?

I'm using the back button on the phone but I believe its the same as calling NavigationService.GoBack(), which navigates to the previous page on the stack but the constructor is not called in my View or ViewModel.

1

There are 1 best solutions below

2
On BEST ANSWER

You can hook in a base Page class the OnNavigatingTo event and call a method on your ViewModel. I don't have a VS with me but a pseudo-code would be:

in MyBasePAge : Page

public void OnNavigatingTo(object sender, eventargs e)
{
   var vm = this.DataContext as BaseViewModel;
   if(vm != null)
   {
      vm.Initialize();
   }
 }

you can do the same before leaving the page:

public void OnNavigatingFrom(object sender, eventargs e)
{
   var vm = this.DataContext as BaseViewModel;
   if(vm != null)
   {
      vm.Save();
   }
 }