MvvmCross - 遇到ViewModel注册问题

时间:2015-10-07 15:45:36

标签: xamarin xamarin.android mvvmcross

我有一个错误,我不知道为什么会得到。

ShellPage.cs:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        fragmentManager = FragmentManager;

        RegisterFragments(bundle);

        .
        .
        .

        ViewModel.ShowMenu();
        ViewModel.ShowFirstContent();
    }

    private void RegisterFragments(Bundle bundle)
    {
        RegisterFragment<MenuContent, MenuContentViewModel>(typeof(MenuContent).Name);
        RegisterFragment<AddChildContent, AddChildContentViewModel>(typeof(AddChildContent).Name);
    }

    public bool Show(MvxViewModelRequest request, Bundle bundle)
    {
        .
        .
        .

        if (request.ViewModelType == typeof(MenuContentViewModel))
        {
            ShowFragment(typeof(MenuContent).Name, Resource.Id.left_drawer, bundle);
            return true;
        }
        else
        {
            ShowFragment(request.ViewModelType.Name, Resource.Id.content_frame, bundle);
            return true;
        }
    }

ShellPageViewModel.cs

    public class ShellPageViewModel : BaseViewModel
    {
        public void ShowMenu()
        {
            ShowViewModel<MenuContentViewModel>();
        }

        public void ShowFirstContent()
        {
            ShowViewModel<SelectChildContentViewModel>();
        }
    }

基本上,当调用 ShowFirstContent ()时,我收到以下错误:

    Cirrious.CrossCore.Exceptions.MvxException: Could not find tag: SelectChildContentViewModel in cache, you need to register it first.

当从 OnCreate ()调用 RegisterFragment ()时,它没有引发任何错误,因此我假设它正确注册了片段和视图模型。

我做错了吗?

我使用的代码全部基于James Montemango的代码:

https://github.com/jamesmontemagno/Xam.NavDrawer/tree/master/Material%20(Lollipop%20Style)/MvvmCross

1 个答案:

答案 0 :(得分:2)

那里的代码有一些严重的错误。我建议您查看:https://github.com/MvvmCross/MvvmCross-AndroidSupport/tree/master/Samples

那里使用的代码是:

    private void RegisterForDetailsRequests(Bundle bundle)
    {
        RegisterFragment<MenuFragment, MenuViewModel>(typeof(MenuViewModel).Name, bundle);
        RegisterFragment<ExamplesFragment, ExamplesViewModel>(typeof(ExamplesViewModel).Name, bundle);
        RegisterFragment<SettingsFragment, SettingsViewModel>(typeof(SettingsViewModel).Name, bundle);
    }

    public void RegisterFragment<TFragment, TViewModel>(string tag, Bundle args)
        where TFragment : IMvxFragmentView
        where TViewModel : IMvxViewModel
    {
        var customPresenter = Mvx.Resolve<IMvxFragmentsPresenter>();
        customPresenter.RegisterViewModelAtHost<TViewModel>(this);
        RegisterFragment<TFragment, TViewModel>(tag);
    }