相关疑难解决方法(0)

如何解析在 ViewModel 内的 builder.Services 中注册的服务?

摘要:我希望使用 MAUIbuilder.Services来解析 ViewModel 中的服务,但我不明白该怎么做。

我可以创建自己的IServiceProvider,但我希望避免所需的样板代码,因此我寻求“标准 MAUI”解决方案。

我添加了以下行MauiProgram.CreateMauiApp()

builder.Services.AddSingleton<IAlertService, AlertService>();
Run Code Online (Sandbox Code Playgroud)

以及相应的声明(在其他文件中):

public interface IAlertService
{
    // ----- async calls (use with "await") -----
    Task ShowAlertAsync(string title, string message, string cancel = "OK");
    Task<bool> ShowConfirmationAsync(string title, string message, string accept = "Yes", string cancel = "No");
}

internal class AlertService : IAlertService
{
    // ----- async calls (use with "await") -----

    public Task ShowAlertAsync(string title, string message, string cancel = "OK")
    {
        return Application.Current.MainPage.DisplayAlert(title, message, cancel); …
Run Code Online (Sandbox Code Playgroud)

maui

5
推荐指数
3
解决办法
8673
查看次数

标签 统计

maui ×1