.NET MAUI全局样式失效抛出XamlParseException异常求助
.NET MAUI全局样式调用异常解决方法
异常信息:
Microsoft.Maui.Controls.Xaml.XamlParseException: Position 10:37. Type converter failed: Exception has been thrown by the target of an invocation.
Microsoft.Maui.Controls.Xaml.XamlParseException: Position 8:34. StaticResource not found for key Primary.
问题根源
你的App.xaml中,自定义样式直接放在了<Application.Resources>节点下,而非嵌套在内部的<ResourceDictionary>中。<Application.Resources>仅允许包含一个ResourceDictionary实例,额外的元素会破坏资源字典结构,导致默认合并的Colors.xaml和Styles.xaml中的资源(如Primary)无法被正确解析,同时自定义样式的作用域也不符合预期。
修正后的App.xaml代码
<?xml version = "1.0" encoding = "UTF-8" ?> <Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyApp" x:Class="MyApp.App"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Styles/Colors.xaml" /> <ResourceDictionary Source="Resources/Styles/Styles.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- 将自定义样式移至ResourceDictionary内部 --> <Style x:Key="redLabelStyle" TargetType="Label"> <Setter Property="TextColor" Value="Red"/> <Setter Property="FontSize" Value="Small"/> <Setter Property="FontAttributes" Value="Bold"/> </Style> <Style TargetType="Label"> <Setter Property="TextColor" Value="Green"/> <Setter Property="FontSize" Value="Small"/> <Setter Property="FontAttributes" Value="Bold"/> </Style> </ResourceDictionary> </Application.Resources> </Application>
修正逻辑
- 所有资源(合并字典、自定义样式等)必须放在
<ResourceDictionary>内部,这是.NET MAUI资源系统的硬性要求。 - 合并字典优先级高于自定义样式,确保默认项目的资源(如
Primary颜色)能被正确加载和引用。 - 修正后,
MainPage.xaml中引用的redLabelStyle静态资源可被正确识别,全局默认Label样式也会正常生效,同时解决Primary资源找不到的异常。
内容的提问来源于stack exchange,提问作者Dinesh Falwadiya
相关产品推荐
相关产品推荐

