Search code examples
androidandroid-fragmentsxamarinmvvmcrossandroid-dialogfragment

Multiple instances of ViewModel being created when opening a dialog fragment using MvvmCross


I've recently started using MvvmCross 5 and using the new INavigationService.

However, I've been unable to find any new ways of presenting Dialog Fragments so I'm still using my old method in a custom presenter (MvxFragmentsPresenter) as follows:

protected override void ShowFragment(MvxViewModelRequest request)   
{

    var currentActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity;
    var appActivity = currentActivity as MvvmCross.Droid.FullFragging.Views.MvxActivity;

                if (appActivity != null)
                {
                    var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
                    var viewModel = loaderService.LoadViewModel(request, null);

                    if (request.ViewModelType == typeof(ExampleViewModel))
                    {
                        var dialogFragment = new ExampleDialogFragment();
                        dialogFragment.ViewModel = (ExampleViewModel)viewModel;
                        dialogFragment.SetStyle(DialogFragmentStyle.Normal, Resource.Style.MainDialogTheme);
                        dialogFragment.Show(appActivity.FragmentManager, ExampleDialogFragment.DialogTag);

                        return;
                    }
    }

The problem I'm having is when I need to pass parameters into this dialog fragment, the navigation service creates the view model with the correct parameters but when it goes to show the fragment, the custom presenter then constructs a new view model without any parameters and sets it to the new dialog fragment.

I have tried using MvxDefaultViewModelLocator instead of the Loader but this just does the same thing.

var locatorService = Mvx.Resolve<IMvxViewModelLocator>();
var viewModel = locatorService.Load(request.ViewModelType, new MvxBundle(request.ParameterValues), null);

Is there a new way to open dialog fragments so the view model that's created with parameters can be assigned to it?

Thanks for any pointers.


Solution

  • We added built-in support for Dialogs in https://github.com/MvvmCross/MvvmCross/pull/2099 This is currently available on Myget and will be released as part of the next MvvmCross release. We are also working on making a more permanent fix for multiple viewmodel instances.