Search code examples
mvvmxamarin.formsprismcode-structure

Use Feature Folders with Prism


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?


Solution

  • 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);
    });