在 Maui 内容页面视图中未识别视图模型

View model not being recognized within Maui Content Page View

我试图从 Maui 的角度理解服务,但注入并没有在视图中重新定位它。

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

查看

<?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>

代码隐藏

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

要让 Maui 应用依赖注入,您需要声明应该在其中进行注入的视图模型。

将此行添加到构建器:

builder.Services.AddTransient<MenusViewModel>();

顺便说一句,如果有很多视图和视图模型要添加到 DI 服务中,可以像这样更简洁一点:

var diTypes = new List<Type> { typeof(MainPage), typeof(Page2), typeof(Page3), typeof(Page4) };
diTypes.ForEach(ty => builder.Services.AddTransient(ty));