首页 > 解决方案 > Xamarin 表单 - 将参数传递给 xaml 文件中指定的 bindingcontext 视图模型

问题描述

我有一个带有条目的 xaml 文件。我将特定条目绑定到特定视图模型。但是视图模型需要一个导航器。如何将导航器从 xaml 文件传递​​到视图模型?

     <Entry  Text="{Binding Signature, Mode=TwoWay}">
        <Entry.BindingContext>
            <vm:SignaturePopupViewModel>
                // I need to pass a navigator..

            </vm:SignaturePopupViewModel>
        </Entry.BindingContext>
    </Entry>

viewmodel 需要一个导航对象。在运行一些代码逻辑后,我使用它来弹出页面以返回上一页。

    public SignaturePopupViewModel(INavigation navigation = null)
    {
        Navigation = navigation;

        SendSignatureCommand = new Command(async () =>
        {
            await SendSignature();
            await Navigation.PopAsync();
        });
    }

标签: xamarin.formsbindingbinding-context

解决方案


您不需要在您的构造函数中使用INavigation navigationSignaturePopupViewModel实现导航。

只需使用一个简单的方法就是

await Application.Current.MainPage.Navigation.PopModalAsync(); 或者

await Application.Current.MainPage.Navigation.PopAsync()

像下面的代码。

   public class SignaturePopupViewModel
{

    public ICommand SendSignatureCommand { protected set; get; }
    public SignaturePopupViewModel( )
    {


        SendSignatureCommand = new Command(async () =>
        {


            await SendSignature();
            // if you use the     MainPage = new NavigationPage( new MainPage()); in 
            //App.xaml.cs use following code.
            await Application.Current.MainPage.Navigation.PopAsync();

             // if not, just use await Application.Current.MainPage.Navigation.PopModalAsync();
        });
    }
}

推荐阅读