Xamarin.Forms How to switch pages using MVVMLight

白昼怎懂夜的黑 提交于 2019-12-13 08:15:15

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/48947588/xamarin-forms-how-to-switch-pages-using-mvvmlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!