How to navigate to a ViewModel that extends an abstract class?

无人久伴 提交于 2019-12-24 07:35:10

问题


I am trying to share viewmodels as much as possible using MVVMCross's suggested assembly architecture:

MyApp.App
└ ViewModels
  ├ GlobalViewModel1
  └ GlobalViewModel2 (abstract)

MyApp.Droid
├ Views
│ ├ View1
│ └ View2
└ ViewModels
  └ ChildOfGlobalViewModel2

MyApp.Store
├ Views
│ ├ View1
│ └ View2
└ ViewModels
  └ ChildOfGlobalViewModel2

I can correctly navigate to View1 and its associated viewmodel GlobalViewModel1, but it gets more complicated when I want to navigate to View2 because its viewmodel varies slightly from one platform to another.

I assumed that if I registered Mvx.RegisterType<GlobalViewModel2, ChildOfGlobalViewModel2>() on each platform, then when GlobalViewModel1 would be able to navigate by using this.ShowViewModel<GlobalViewModel2>(). Apparently I was wrong, since I get an exception when the app tries to instantiate the abstract class.

I do view look up initialization manually by overriding InitializeViewLookup, so I tried associating the view to the parent and the child classes, but none of those configurations was successful.

I already solved the problem once by injecting the desired behaviour because it was pertinent to encapsulate it in a class, but in some cases this approach would only force me to create a number of classes that will make the code less readable and the apps harder to maintain in the future.

Is there some configuration I am missing or should I change my approach? If so, what is the recommended approach?


回答1:


The default setup in MvvmCross is navigation by viewmodel - this doesn't include navigation by inheritance.

You could override parts of mvx in order to support your abstract scenario if you really wanted to. However, I think this would be more effort than it is worth.

Instead, I would suggest either:

  • registering a service IG2Service which has a single property called G2Type. Each platform could then set the VM Type for your Global2 and your navigation could then call the get before performing the navigation. Note: using this technique, you won't be able to use the ShowViewModel<T> overrides to navigate this way, but the non-generic overrides should work fine.
  • or (if possible) refactoring your code so that your g2 view models use platform specific code via dependency injection rather than via inheritance.


来源:https://stackoverflow.com/questions/24821421/how-to-navigate-to-a-viewmodel-that-extends-an-abstract-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!