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

- **ID:** `dotnet/wpf-resource-dictionary-key-not-found`
- **领域:** dotnet
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 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 | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **Changing StaticResource to DynamicResource everywhere.** — 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. (70% 失败率)
- **Adding the resource key with a null value in the same dictionary.** — A null resource will cause a NullReferenceException when used; it does not solve the missing definition issue. (90% 失败率)
- **Deleting the XAML file and recreating it from scratch.** — This is an overreaction; the root cause is a missing resource definition, not file corruption. (100% 失败率)
