Xamarin 社区工具包弹出 MVVM 绑定问题

问题描述

尝试在 Xamarin Forms MVVM 模式项目中使用 Xamarin 社区工具包弹出窗口,目标平台为 IOS 和 Android。弹出窗口正在出现,但是我无法绑定以从视图模型显示我的 PopUpMessage 字符串。这是我的代码

XAML:

<xct:Popup.BindingContext>
    <viewmodels:ProviderApplicationviewmodel />
</xct:Popup.BindingContext>

<StackLayout Style="{StaticResource PopupLayout}">
    <Label Style="{StaticResource Title}" 
            Text="Application Status" />
    <BoxView Style="{StaticResource Divider}" />
    <Label Style="{StaticResource Content}" 
            Text="{Binding PopUpMessage}"
           TextColor="Black"/>
    <Button Text="OKAY"
            Style="{StaticResource ConfirmButton}"
            Clicked="Button_Clicked" />
</StackLayout>

背后的代码

    public partial class ProviderApplicationPopup : Popup
{
    public ProviderApplicationPopup()
    {
        InitializeComponent();
    }

    void Button_Clicked(object sender,System.EventArgs e) => dismiss(null);
}

视图模型:

    private string popupmessage;
    public string PopUpMessage { set { SetProperty(ref popupmessage,value); } get { return popupmessage; } }

viewmodel 弹出导航:

   if (response == "True")
        {
            PopUpMessage = "Your application has been submitted!";
            Navigation.ShowPopup(new ProviderApplicationPopup());
            IsBusy = false;
            return;
        }

Missing Text

解决方法

在我看到其余代码之前我无法判断,尽管我认为问题在于您如何实例化 ProviderApplicationPopup

首先您要设置 PopupMessage 值,然后实例化 ProviderApplicationPopup 但可能 ProviderApplicationPopup 也实例化具有空 PopupMessage 值的新 ViewModel。

因此您可以在实例化 ProviderApplicationPopup 时直接传递字符串,例如 new ProviderApplicationPopup("Your application has been submitted!") 然后在构造函数中设置值

P.S:或者您也可以先实例化 ViewModel,然后将其传递给 ProviderApplicationPopup,然后绑定它。

编辑:

var viewModel = new ProviderApplicationViewModel()
{
    PopUpMessage = "Your application has been submitted!";
}
Navigation.ShowPopup(new ProviderApplicationPopup(viewModel));

//------------- In ProviderApplicationPopup -------------

public ProviderApplicationPopup(ProviderApplicationViewModel viewModel)
{
    BindingContext = viewModel;
}