-1

I'm currently working on a Xamarin.forms project using .NET Standard as code sharing strategy. I try to use the MVVM pattern by using the MvvmLightLibsStd10 library. I already successfully setup the MVVM structure by using this tutorial: https://www.linkedin.com/pulse/build-xamarinforms-net-standard-mvvm-light-app-rafael-carvalho

I can't use Navigation.PushAsync(new Page()); because it only works in code behind and not in the ViewModel.

I already tried to Pass Navigation trough the VM constructor, like describe over here:
Xamarin.form Page Navigation in mvvm

But when I try this method, an error occurred at "LoadApplication(new DemoMVVM2.App());" in MainPage.

How can I switch pages using MVVM Xamarin.Forms with MVVMLight (based on the code from my first url)?

but I have no Idea how I can switch Pages via the ViewModel and keeping the header with back button.

appyGeek
  • 45
  • 1
  • 8

2 Answers2

1

Generally when working with MVVMLight you'll be using a NavigationService. This class can be constructor injected in your VM, thanks to the build in IOC in MVVMLight. With it you can do Navigate and GoBack in your VM, triggering a real navigation on the current stack.

Only thing that you maybe missed, is the fact that you need to write one yourself for Xamarin forms. But Laurent Bugnion ( the owner of MVVMLight ) supplied an example available here: https://github.com/lbugnion/sample-2016-vslive-crossplatform/blob/master/Flowers/Flowers.Forms/Flowers.Forms/Helpers/NavigationService.cs

Depechie
  • 6,102
  • 24
  • 46
0

You can pass a callback to your ViewModel(VM) and on Command or whatever action call your navigation code which is in your page (View). this way you can keep your navigation code in your page and your binding logic in your ViewModel.

interface NavHandler{
    void navigateToSomeView();
}

public class MyPage : ContentPage,NavHandler{
     public MyPage(){
         BindingContext = new MyViewModel(this);
     }
     void navigateToSomeView(){
         Navigation.PushAsync(new Page2());
     }
} 

public class MyViewModel{
    NavHandler handler;
    public MyViewModel(NavHandler handler){
        this.handler = handler
    }
    //Your action
    this.btnClicked = new Command(async()=>{
        handler.navigateToSomeView()
    }
}
Fahadsk
  • 1,099
  • 10
  • 24
  • I tried your advice but now, everytime when I run the app, whenever it is UWP or Android, I got 'No parameterless constructor defined for this object.' However App only have 1 ctor which actually is parameterless. You can download my source code over here: https:// we.tl/byHWdsjyFN – appyGeek Feb 23 '18 at 14:18
  • you should call constructor with parameter as shown in the code above `BindingContext = new MainViewModel(this);` which is the constructor you have defined in your `MainViewModel.cs` – Fahadsk Feb 23 '18 at 14:30