dotnet resource_error ai_generated true

System.Windows.Markup.XamlParseException: “Provide value on 'System.Windows.StaticResourceExtension'”引发了异常。行号“42”,行位置“10”。

System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '42' and line position '10'.

ID: dotnet/wpf-resource-dictionary-key-not-found

其他格式: JSON · Markdown 中文 · English
90%修复率
84%置信度
1证据数
2023-11-08首次发现

版本兼容性

版本状态引入弃用备注
WPF on .NET Core 3.1 active
WPF on .NET 5.0 active
WPF on .NET 6.0 active
WPF on .NET 7.0 active
WPF on .NET 8.0 active
.NET Framework 4.7.2 active
.NET Framework 4.8 active

根因分析

WPF XAML 中的 StaticResource 引用指向了一个未在任何合并的 ResourceDictionary 中定义的资源键,或者在同一字典中定义得太晚,导致运行时查找失败。

English

A StaticResource reference in WPF XAML points to a resource key that is not defined in any merged ResourceDictionary or is defined later in the same dictionary, causing a lookup failure at runtime.

generic

官方文档

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/resources-overview?view=netdesktop-8.0

解决方案

  1. Define the missing resource key in the correct ResourceDictionary. For example, in App.xaml: <Application.Resources><ResourceDictionary><SolidColorBrush x:Key="MyBrush" Color="Blue"/></ResourceDictionary></Application.Resources>
  2. Ensure resource dictionaries are merged in the correct order. The resource must be defined before it is referenced. Move the resource definition above the element that uses it in the same file or merge dictionaries in the correct sequence.
  3. Use DynamicResource as a temporary workaround if the resource is defined but not available at load time (e.g., defined in a merged dictionary that is loaded later). However, prefer fixing the StaticResource lookup.

无效尝试

常见但无效的做法:

  1. Changing StaticResource to DynamicResource everywhere. 70% 失败

    DynamicResource resolves at runtime but may cause performance issues and still fail if the resource is never defined; it also changes the behavior of resource updates.

  2. Adding the resource key with a null value in the same dictionary. 90% 失败

    A null resource will cause a NullReferenceException when used; it does not solve the missing definition issue.

  3. Deleting the XAML file and recreating it from scratch. 100% 失败

    This is an overreaction; the root cause is a missing resource definition, not file corruption.