Tyler
Tyler

Reputation: 1049

How do you refresh your ViewModel when navigating back using MVVM

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.

Upvotes: 4

Views: 3118

Answers (1)

MatthieuGD
MatthieuGD

Reputation: 4592

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();
   }
 }

Upvotes: 6

Related Questions