Sharing Views With MvvmCross

MvvmCross uses IMvxViewsContainer to determine which ViewController it needs to initialize. The IMvxViewsContainer implementation uses both Convention OR the Generic argument TViewModel of MvxViewController<TViewModel> to determine the mapping TViewModel <=> ViewController.

Problem comes when you have very similar ViewModels with slightly different behavior but identical UIs. With the built in IMvxViewsContainer implementation, you end-up having to create duplicate Views on the Platform side that each map to its own ViewModel.

To change that behavior, you can add additional mappings to IMvxViewsContainer by overriding the Setup class on the platform. For iOS, this may look like this:

    protected override void InitializeViewLookup()
        {
            base.InitializeViewLookup();
            var viewModelViewLookup = new Dictionary<Type, Type>{
                { typeof(FirstChildViewModel), typeof(CommonChildViewController) },
                { typeof(SecondChildViewModel), typeof(CommonChildViewController) },
            };

            var container = Mvx.IoCProvider.Resolve<IMvxViewsContainer>();
            container.AddAll(viewModelViewLookup);
        }

Next time you request FirstChildViewModel or SecondChildViewModel, IMvxViewsContainer will return a new instance of CommonChildViewController, this way you don’t end up with duplicated views.

Happy coding!