When I inject the mainpage to the App class constructor I am getting StaticResource not found for key But if I don't inject the Mainpage on the App constructor it works.
I have a global resource Theme file which I call on the App.xaml.cs where i declare the static resource:
<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>
This is my App.cs file:
public App(MainPage mainPage)
{
InitializeComponent();
MainPage = mainPage;
}
The following code is in the 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>
I have added the MainPage to the mauiprogram.cs class
builder.Services.AddTransient<MainPage>();
CodePudding user response:
I have created a new project to test your code and met the same error. Then I added two break point. One is on the MainPage's construction method and the other is on the App.cs's construction method.
I found that the mainpage's construction method excute before the app.cs' when I used builder.Services.AddTransient<MainPage>();
. So the error appeared.
Finally, you can follow up this issue about Can't use App.xaml resources after Dependency Injection .NET MAUI on the github. Or just use the DynamicResource instead of the StaticResource such as:
<StackLayout BackgroundColor="{DynamicResource SecondaryBackroundColor}"
I have tried it. Using the DynamicResource works.