Home > Enterprise >  View model not being recognized within Maui Content Page View
View model not being recognized within Maui Content Page View

Time:06-05

I am trying to understand services in terms of Maui but the injection is not reconizing it in the view.

namespace FoodOrder.ViewModels
{
public class MenusViewModel
{
    IMenuServiceInterface _menuServiceInterface;
    IFoodOrderHttpClientInterface _foodOrderHttpClientInterface;
    public MenusViewModel(IMenuServiceInterface 
       menuServiceInterface, IFoodOrderHttpClientInterface 
       foodOrderHttpClientInterface)
    {
        _foodOrderHttpClientInterface = foodOrderHttpClientInterface;
    }   
}
}

View

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        x:Class="FoodOrder.Pages.MenuPage"
        xmlns:vm="clr-namespace:FoodOrder.ViewModels"
        Title="MenuPage">
<ContentPage.BindingContext>
<vm:MenusViewModel />
</ContentPage.BindingContext>
<StackLayout>
<Label Text="Welcome to .NET MAUI!"
        VerticalOptions="Center" 
        HorizontalOptions="Center" />
</StackLayout>
</ContentPage>

Code Behind

public partial class MenuPage : ContentPage
{
public MenuPage(MenusViewModel viewModel)
{
    InitializeComponent();
    BindingContext = viewModel;
}
}

MauiProgram.cs

public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        });
    builder.Services.AddTransient<IFoodOrderHttpClientInterface, 
     FoodOrderHttpClientServices>();

    return builder.Build();
}
}

CodePudding user response:

To have Maui apply Dependency Injection, you also need to declare the viewmodel in which injection should occur.

Add this line to builder:

builder.Services.AddTransient<MenusViewModel>();
  • Related