Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
Tyler Avatar asked Nov 15 '25 18:11

Tyler


1 Answers

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();
   }
 }
like image 101
MatthieuGD Avatar answered Nov 18 '25 19:11

MatthieuGD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!