Forms如何使用MVVMLight切换页面

Forms如何使用MVVMLight切换页面

本文介绍了Xamarin.Forms如何使用MVVMLight切换页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 .NET Standard 作为代码共享策略的Xamarin.forms项目.我尝试通过使用 MvvmLightLibsStd10 库来使用MVVM模式.通过使用本教程,我已经成功设置了MVVM结构: https://www.linkedin. com/pulse/build-xamarinforms-net-standard-mvvm-light-app-rafael-carvalho

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

我不能使用Navigation.PushAsync(new Page());因为它只能在后面的代码中工作,而不能在ViewModel中工作.

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

我已经尝试通过VM构造函数传递导航,例如在此处进行描述:
mvvm中的Xamarin.form页面导航

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

但是当我尝试这种方法时,在"LoadApplication(new DemoMVVM2.App());"处发生了错误.在MainPage中.

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

如何使用带有MVVMLight的MVVM Xamarin.Forms切换页面(基于我的第一个URL的代码)?

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

但是我不知道如何通过ViewModel切换页面并保持标题带有后退按钮.

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

推荐答案

您可以将回调传递给ViewModel(VM)并在Command上传递,也可以通过任何操作调用页面(视图)中的导航代码.这样,您就可以将导航代码保留在页面中,并将绑定逻辑保留在ViewModel中.

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

这篇关于Xamarin.Forms如何使用MVVMLight切换页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:45