Search code examples
win-universal-appuwpmvvmcross

ShowViewModel does not work if called too early


In MvvmCross 4.1.4 for Window Universal App (UWP) platform, if we call ShowViewModel too early within ViewModel (like in Constructor, Init, or Start event) then it does not navigate to another model.

public class FirstViewModel : MvxViewModel
{
  public FirstViewModel()
  {
     ShowViewModel<SecondViewModel>();
  }
}

Note that it works just fine for iOS and Android platform.


Solution

  • It is a bug of MvvmCross (according to this https://github.com/MvvmCross/MvvmCross/issues/1223).

    The work around solution is to trigger the navigation from some events like View_Loaded or View_GotFocus within the View:

      public sealed partial class FirstView : MvxWindowsPage
      {
                public FirstView()
                {            
                    this.InitializeComponent();
                    this.Loaded += FirstView_Loaded;
                }
    
                private void FirstView_Loaded(object sender, RoutedEventArgs e)
                {   
                    var viewModel = base.ViewModel as FirstViewModel
                    if (viewModel != null)
                    {
                        viewModel.Initialise();
                    }
                }
     }
    

    ViewModel updated:

    public class FirstViewModel : MvxViewModel
    {
      public FirstViewModel()
      {
      }
    
      public void Initialise()
      {
         //Navigate here
         ShowViewModel<SecondViewModel>();
      }
    }