Phu*_*fho 6 c# xaml dependency-injection maui
当我将主页注入到 App 类构造函数时,我得到StaticResource not find for key 但如果我不在 App 构造函数中注入主页,它就会起作用。
我有一个全局资源主题文件,我在App.xaml.cs上调用该文件,在其中声明静态资源:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
<ResourceDictionary Source="Themes/LightTheme.xaml" /> <!--Theme file-->
<ResourceDictionary Source="Themes/DarkTheme.xaml" /> <!--Theme file-->
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)
这是我的 App.cs 文件:
public App(MainPage mainPage)
{
InitializeComponent();
MainPage = mainPage;
}
Run Code Online (Sandbox Code Playgroud)
以下代码位于 MainPage.xaml 中:
<StackLayout BackgroundColor="{StaticResource SecondaryBackroundColor}" Grid.Row="0">
<Image
Source="ic_logo.png"
SemanticProperties.Description="Cute dot net bot waving hi to you!"
HeightRequest="200"
HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
</StackLayout>
Run Code Online (Sandbox Code Playgroud)
我已将MainPage添加到 mauiprogram.cs 类中
builder.Services.AddTransient<MainPage>();
我创建了一个新项目来测试您的代码并遇到了相同的错误。然后我添加了两个断点。一个是MainPage的构造方法,另一个是App.cs的构造方法。
我使用.cs时发现主页的构造方法先于app.cs执行builder.Services.AddTransient<MainPage>();。于是就出现了错误。
最后,您可以在github上跟进Can't use App.xaml resources after Dependency Injection .NET MAUI这个问题。或者只使用 DynamicResource 而不是 StaticResource,例如:
<StackLayout BackgroundColor="{DynamicResource SecondaryBackroundColor}"
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了。使用 DynamicResource 有效。