Xamarin.Forms 如何使用 MVVMLight 切换页面 [英] Xamarin.Forms How to switch pages using MVVMLight

查看:57
本文介绍了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());"处发生了错误在主页中.

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

如何使用 MVVM Xamarin.Forms 和 MVVMLight 切换页面(基于我的第一个 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 切换页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆