.NET MAUI使用DI时资源字典加载失败问题排查
.NET MAUI依赖注入下App.xaml资源字典加载失败问题解决办法
问题原因
核心问题是页面实例化时机早于App.xaml资源字典加载:当通过DI直接把MyFirstPage注入到App的构造函数时,DI容器会在App的InitializeComponent()方法执行前就创建页面实例。而InitializeComponent()正是负责加载App.xaml中定义的资源字典的关键步骤,此时页面渲染时引用{StaticResource Primary}自然找不到对应的资源。
解决办法
方案1:延迟页面实例化(推荐)
通过Func<T>或Lazy<T>让页面在App资源加载完成后再创建,避免DI提前实例化页面。
修改MauiProgram.cs的服务注册:
var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); }); builder.Services.AddSingleton<PropertyListViewModel>(); builder.Services.AddTransient<MyFirstPage>(); // 根据页面生命周期选择Transient/Singleton修改App.xaml.cs的构造函数:
public partial class App : Application { public App(Func<MyFirstPage> firstPageFactory) { InitializeComponent(); // 等资源加载完成后再创建页面 MainPage = firstPageFactory(); } }也可以用
Lazy<T>实现延迟加载:public App(Lazy<MyFirstPage> firstPageLazy) { InitializeComponent(); MainPage = firstPageLazy.Value; }
方案2:改用AppShell管理页面导航
恢复使用AppShell,让页面在导航触发时才实例化,此时App的资源字典已经加载完成:
修改App.xaml.cs:
public partial class App : Application { public App() { InitializeComponent(); MainPage = new AppShell(); } }在AppShell.xaml中注册路由:
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:views="clr-namespace:MyApp.Mobile.Views" x:Class="MyApp.Mobile.AppShell"> <ShellContent Route="MyFirstPage" ContentTemplate="{DataTemplate views:MyFirstPage}" /> </Shell>确保MauiProgram.cs中已注册页面和ViewModel:
builder.Services.AddSingleton<PropertyListViewModel>(); builder.Services.AddTransient<MyFirstPage>();
额外检查点
- 确认
Colors.xaml和Styles.xaml的Build Action设置为MauiXaml,Copy to Output Directory设置为Do not copy(默认即可)。 - 检查资源字典的路径是否正确,虽然移除DI后能正常运行,但路径错误也可能在某些场景下触发类似问题。
内容的提问来源于stack exchange,提问作者Thierry
相关产品推荐
相关产品推荐

