How to update ViewModel while navigating using MVVM

When navigating the back button on the phone, how can I update the ViewModel?

I use the back button on the phone, but I find it to be the same as calling NavigationService.GoBack (), which moves to the previous page on the stack, but the constructor is not called in my view or ViewModel.

+3
source share
1 answer

You can connect the base class of the page to the OnNavigatingTo event and call the method on your ViewModel. I don't have VS with me, but the pseudocode will 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();
   }
 }
+6
source

Source: https://habr.com/ru/post/1791043/


All Articles