Luis Guzman
Luis Guzman

Reputation: 65

Can't use App.xaml resources after Dependency Injection .NET MAUI

I have an application that uses mvvm pattern with Community Toolkit features. I am trying to use Dependency Injection to use an ApiService with its interface in my viewmodels, but after following the steps described here, I can't access to App.xaml Resources (specifically colors), the intellisense works when I am writing code in XAML, but it doesn´t work after running. It is important to notice that I was using colors from resources correctly before trying to use Dependency Injection and changing the ViewModel - View linking method to the one described here, but I was unable to use ApiService. Here is my code.

App.xaml.cs (Login page is my first page):

public App(LoginPage page)
{
    InitializeComponent();
    MainPage = page;
}

LoginPage.xaml.cs

public partial class LoginPage : ContentPage
{
  public LoginPage(LoginPageViewModel loginPageViewModel)
  {
    BindingContext = loginPageViewModel;
    InitializeComponent();
  }
}

LoginPageViewModel

public LoginPageViewModel(IApiService apiService)
    {
        _apiService = apiService;
        Opacity = 1f;
        IsEnabled = true;
        IsRunning = false;
    }

LoginPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="NewScholarApp.Views.LoginPage"
         Title="LoginPage"
         xmlns:vm="clr-namespace:NewScholarApp.ViewModels"
         x:DataType="vm:LoginPageViewModel"
         BackgroundColor="{StaticResource GreenSchool}">

MauiProgam.cs

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>().UseMauiCommunityToolkit().ConfigureViewModels().ConfigureServices().ConfigureViews()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        });

    //builder.Services.AddSingleton<ApiService>();

    return builder.Build();
}

RegisterViews and ViewModels

public static MauiAppBuilder ConfigureViews(this MauiAppBuilder mauiAppBuilder)
    {
        mauiAppBuilder.Services.AddTransient<LoginPage>();

        return mauiAppBuilder;
    }

public static class RegisterViewModels
{

    public static MauiAppBuilder ConfigureViewModels(this MauiAppBuilder mauiAppBuilder)

    {
        mauiAppBuilder.Services.AddSingleton<LoginPageViewModel>();

        return mauiAppBuilder;
    }
}

Open issue: https://github.com/dotnet/maui/issues/11485

Upvotes: 1

Views: 732

Answers (1)

Liqun Shen-MSFT
Liqun Shen-MSFT

Reputation: 8220

This question is related to Cannot use StaticResources for resources in App.xaml. IndianaGary's comment indicated that you could try a DynamicResource.

Upvotes: 1

Related Questions