1

I have a Xamarin.Forms project that uses Prism, and the number of Views and View Models is growing unwieldy.

In web projects I usually use Feature Folders, grouping relevant code together, e.g.:

  • Features
    • Home
      • Home.cshtml
      • Home.cs
      • Home.js
      • HomeController.cs
    • Widgets
      • List.cshtml
      • List.cs
      • List.js
      • Detail.cshtml
      • Detail.cs
      • Detail.js
      • WidgetsController.cs

I'd like to do the same thing in the Xamarin.Forms project, but I don't know how to configure Prism to look for Views and View Models in these locations instead of the Views and ViewModels folders?

Cocowalla
  • 13,822
  • 6
  • 66
  • 112

2 Answers2

3

You can either manually register view models for views or modify the convention that the ViewModelLocator uses to find the view model for a view.

An example can be found here, although this just replicates the original convention, it shows where to start with your modification:

ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver( viewType => viewModelType );

Also, this blog post describes how to change the convention to find view models that reside besides the view in the same folder:

ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
{
    var viewName = viewType.FullName;
    var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
    var viewModelName = String.Format(CultureInfo.InvariantCulture, “{0}ViewModel, {1}”, viewName, viewAssemblyName);
    return Type.GetType(viewModelName);
});
Haukinger
  • 10,420
  • 2
  • 15
  • 28
1

While @Haukinger is technically correct that you can set the ViewModelLocationProvider. We recommend that you simply specify the View and ViewModel at registration time. This is much faster as it avoids any Reflection lookup.

containerRegistry.RegisterForNavigation<ViewA, ViewAViewModel>();
Dan Siegel
  • 5,724
  • 2
  • 14
  • 28
  • Right, that's what I meant with "You can [...] manually register view models for views" – Haukinger Aug 12 '19 at 15:01
  • What's the reasoning behind recommending manual registration of Views & ViewModels, vs using `SetDefaultViewTypeToViewModelTypeResolver`? (I get that your example uses DI, but that's possible using `ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver` too) – Cocowalla Aug 12 '19 at 19:24
  • When relying on the ViewModelLocationProvider to automatically resolve the ViewModel based on the conventions there is a reflection lookup cost which can be high particularly on Tier 2-3 devices. By explicitly mapping the relationship in your bootstrap method `App.RegisterTypes` you're providing Prism the explicit mapping allowing it to bypass any reflection costs. Simply put, it's much faster. – Dan Siegel Aug 12 '19 at 19:28