[英]Resolve MainPage from IServiceProvider in Microsoft.Maui.Controls.Application
我创建了一个新的 dotnet maui 项目,并希望从IServiceProvider
解析MainPage
。
我添加到MauiProgram.cs
行builder.Services.AddSingleton<MainPage>();
. 而不是( App.xaml.cs
):
public partial class App : Microsoft.Maui.Controls.Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
}
我想检索或以某种方式访问MauiApp
以从IServiceProvider
解析MainPage
。 像这样的东西:
public partial class App : Microsoft.Maui.Controls.Application
{
public App()
{
InitializeComponent();
var mauiApp = (MauiApp)this;
MainPage = mauiApp.Services.GetService(typeof(MainPage)) as ContentPage;
}
}
最好的方法是什么?
在 MauiProgram.cs 中:
为您需要的任何服务添加单例:
public static MauiApp CreateMauiApp()
{
builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<IGoodbyeWorldService, GoodbyeWorldService>();
}
在 App.Xaml.cs 中:
在 App 方法的参数中包含 MainPage 并分配给 MainPage:
public App(MainPage page)
{
InitializeComponent();
MainPage = page;
}
然后在 MainPage.xaml.cs 中包含你需要的服务在 arguments 中:
public MainPage(IGoodbyeWorldService service)
{
InitializeComponent();
lblOne.Text = service.SayGoodbye();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.