James Lavery
James Lavery

Reputation: 949

Custom ViewModel registration with Prism and MAUI - ViewModelLocationProvider the right way to do it?

We're migrating a Forms application, which uses Prism, to MAUI, and had a custom ViewModelLocator for one of our pages, implemented by overriding ConfigureViewModelLocator in App.xaml.cs.

With a Prism MAUI application, where do we now configure this?

I've tried using ViewModelLocationProvider.Register in .OnAppStart:

 ViewModelLocationProvider.Register(typeof(TestPage).ToString(),() =>
 {
     // Code to get the ViewModel here...
     return testPageViewModel;
 });

but the above code in the lambda is never getting called.

Is this the right place to do it? Do ViewModelLocationProvider registrations work under MAUI?

Upvotes: 1

Views: 418

Answers (2)

Tommy Baggett
Tommy Baggett

Reputation: 650

See PrismAppBuilder.ConfigureViewTypeToViewModelTypeResolver. You will receive your view's Type and are expected to return your view model's type. This needs to be added to your MauiProgram class inside of the UsePrism extension method handling.

Upvotes: 0

Swati Chandra
Swati Chandra

Reputation: 36

The registration of ViewModelLocationProvider should be done using Dependency Injection like below.

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>();
        
        // register the services, viewmodels or views here
        builder.Services.AddSingleton<ViewModelLocationProvider>();

        return builder.Build();
    }
}

Have a look at this example of implementing Dependency Injection: https://github.com/jfversluis/MauiDependencyInjectionSample/tree/main

Upvotes: -2

Related Questions