在Android上的MvxTabbbedPage中时,未调用MvvmCross初始IMvxViewModel ViewAppeared

时间:2019-02-08 12:15:39

标签: android xamarin.forms mvvmcross

我们的Xamarin.Forms项目中有一个MvxTabbedPage和一个子MvxContentPage

在Android上,我发现第一次显示ViewAppeared时没有调用我的第一个子页面上的MvxTabbedPage替代。

切换标签时,随后会正确调用它。

我正在ViewAppearing中为MvxTabbedPage的PageModel初始化PageModels,如下所示:

public override async void ViewAppearing()
{
    await ShowInitialViewModels();
    base.ViewAppearing();
}

private bool viewModelsInitialised = false;
private async Task ShowInitialViewModels()
{
    if (!viewModelsInitialised)
    {
        await _BusyManager.SetBusy();
        var tasks = new List<Task>();
        tasks.Add(_MvxNavigationService.Navigate<HomePageModel>());
        tasks.Add(_MvxNavigationService.Navigate<MyBenefitsPageModel>());
        tasks.Add(_MvxNavigationService.Navigate<ClaimsPageModel>());
        tasks.Add(_MvxNavigationService.Navigate<ContactUsPageModel>());
        tasks.Add(_MvxNavigationService.Navigate<SettingsPageModel>());
        await Task.WhenAll(tasks);
        viewModelsInitialised = true;
        await _BusyManager.SetUnBusy();
    }
}

其他人是否看到过这种行为,和/或我应该做些不同的事情吗?

2 个答案:

答案 0 :(得分:1)

看起来像是这个Forms错误:

https://github.com/xamarin/Xamarin.Forms/issues/3855

此MvvmCross问题引用的

https://github.com/MvvmCross/MvvmCross/issues/2823

(感谢Pedro在Slack上将我指向这个方向:)

答案 1 :(得分:0)

检查mvvmcross的Playground project。您应该在视图模型中单独管理选项卡的初始化,并在后面的XF视图代码中进行管理。

public class YourTabsViewModel : MvxViewModel
{
    private readonly IMvxNavigationService _navigationService;

    public YourTabsViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;

        ShowInitialViewModelsCommand = new MvxAsyncCommand(ShowInitialViewModels);
    }

    public IMvxAsyncCommand ShowInitialViewModelsCommand { get; private set; }

    private async Task ShowInitialViewModels()
    {
        var tasks = new List<Task>
        {
            tasks.Add(_navigationService.Navigate<HomePageModel>();
            tasks.Add(_navigationService.Navigate<MyBenefitsPageModel>());
            tasks.Add(_navigationService.Navigate<ClaimsPageModel>());
            tasks.Add(_navigationService.Navigate<ContactUsPageModel>());
            tasks.Add(_navigationService.Navigate<SettingsPageModel>());
        }

        await Task.WhenAll(tasks);
    }
}

然后在您的XF视图后面的代码上

[MvxTabbedPagePresentation(TabbedPosition.Root, NoHistory = true)]
public partial class YourTabsPage : MvxTabbedPage<YourTabsViewModel>
{
    public YourTabsPage()
    {
        InitializeComponent();
    }

    private bool _firstTime = true;

    protected override void OnAppearing()
    {
        base.OnAppearing();

        if (_firstTime)
        {
            ViewModel.ShowInitialViewModelsCommand.ExecuteAsync(null);

            _firstTime = false;
        }
    }
}