Search code examples
mvvmcross

Register a single View as the View for Multiple ViewModels - MVVMCross


  • MMVMCross
  • Android
  • Windows 8

We had a View, call it FruitView displaying a ViewModel called FruitViewModel. The FruitViewModel can display lists of a particular type of fruit.

This all worked fine.

For a couple of reasons we created AppleViewModel and PearViewModel that inherit from FruitViewModel. They do not do anything, all calls are made to the base viewmodel.

I want to register the FruitView as the View for AppleViewModel and PearViewModel when I try and navigate to them using MvxNavigatingObject.ShowViewModel.

I cannot see how to override the default linking of Views to ViewModels. I read one post that suggested overriding GetViewModelViewLookup in the Setup class but that does not seem to exist. I also looked at CustomPresenters but that did not look like the right approach.

Anyone else done this?

Thanks

Pat


Solution

  • After spotting this question How to navigate to a ViewModel that extends an abstract class? (not one of the suggesting when i was posting) I found InitializeViewLookup that can be overridden in each platform's Setup.cs. I am augmenting the current mappings rather than replacing so have called base.InitializeViewLookup first.

    protected override void InitializeViewLookup()
    {
        base.InitializeViewLookup();
    
        var viewModelViewLookup = new Dictionary<Type, Type>()
        {
            { typeof(AppleViewModel), typeof(FruitView) },
            { typeof(PearViewModel), typeof(FruitView) }
           };
    
        var container = Mvx.Resolve<IMvxViewsContainer>();
        container.AddAll(viewModelViewLookup);
    }
    

    Thanks

    Pat