我想从xamarin形式的子对话框页面调用父页面方法

问题描述 投票:0回答:1

我对xamarin表格是陌生的,现在已经尝试了大约三个小时来理解它。

我使用下面的代码打开对话框:等待NavigationService.NavigateAsync(“ DialogPopupManualConfigPage”);

在“ DialogPopupManualConfigPage”对话框中,有一个“完成”和“取消”按钮。单击“完成”时,我想调用位于调用对话框的父页面中的函数。

public DialogPopupManualConfigPage(INavigationService navigationService) : base(navigationService)
    {
        CurrentProgressPercent = string.Format("{0:F0}% complete", 0.00);

        ConfigureCommand = new DelegateCommand(async () => await ConfigureAsync());
        CloseCommand = new DelegateCommand(async () => await CloseAsync());
    }

    private async Task ConfigureAsync()
    {
        //call a method from parent viewModel
    }


    private async Task CloseAsync()
    {
        await NavigationService.GoBackAsync();
    }

任何帮助将不胜感激。谢谢!

xamarin xamarin.forms xamarin.ios
1个回答
1
投票

最简单的方法是将viewModel引用传递给子页面:

ChildPage

myViewModel parentViewModel;

public DialogPopupManualConfigPage(myViewModel vm)
{
    InitializeComponent();

    parentViewModel = vm;
}

private async Task ConfigureAsync()
{
    //call a method from parent viewModel

    parentViewModel.test();
}

ParentPage

public partial class MainPage : ContentPage
{

    myViewModel currentViewModel;
    public MainPage()
    {
        InitializeComponent();
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        Navigation.PushAsync(new DialogPopupManualConfigPage(currentViewModel));
    }
}

public class myViewModel {
    public void test() {}
}

使用messagingCenter的示例:

ChildPage

private async Task ConfigureAsync()
{
    //call a method from parent viewModel
    MessagingCenter.Send<Object>(new Object(), "Hi");
}

ParentPage

myViewModel currentViewModel;
public MainPage()
{
    InitializeComponent();

    MessagingCenter.Subscribe<Object>(new Object(), "Hi", (sender) =>
    {
        // Do something whenever the "Hi" message is received

        currentViewModel.test();
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.