问题
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
IG2Servicewhich has a single property calledG2Type. Each platform could thensetthe VM Type for your Global2 and your navigation could then call thegetbefore performing the navigation. Note: using this technique, you won't be able to use theShowViewModel<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