---
name: managing-styles-resourcedictionary
description: "Manages WPF Style definitions and ResourceDictionary patterns including BasedOn inheritance and resource merging. Use when building theme systems, organizing resources, or choosing between StaticResource and DynamicResource."
---
# WPF Style & ResourceDictionary Patterns
Effectively managing Style and ResourceDictionary for consistent UI and maintainability.
## 1. Style Basic Structure
### 1.1 Explicit Style (With Key)
```xml
```
### 1.2 Implicit Style (Without Key)
```xml
```
---
## 2. Style Inheritance (BasedOn)
### 2.1 Basic Inheritance
```xml
```
### 2.2 Implicit Style Inheritance
```xml
```
---
## 3. ResourceDictionary
### 3.1 File Structure
```
📁 Themes/
├── 📄 Colors.xaml (Color definitions)
├── 📄 Brushes.xaml (Brush definitions)
├── 📄 Converters.xaml (Converter definitions)
├── 📄 Controls/
│ ├── 📄 Button.xaml (Button styles)
│ ├── 📄 TextBox.xaml (TextBox styles)
│ └── 📄 ListBox.xaml (ListBox styles)
└── 📄 Generic.xaml (Merged dictionary)
```
### 3.2 Colors.xaml
```xml
#2196F3
#1976D2
#BBDEFB
#FF4081
#212121
#757575
#FAFAFA
#FFFFFF
#F44336
#4CAF50
#FFC107
```
### 3.3 Brushes.xaml
```xml
```
### 3.4 Generic.xaml (Merged Dictionary)
```xml
```
### 3.5 Loading in App.xaml
```xml
```
---
## 4. StaticResource vs DynamicResource
### 4.1 Comparison
| Aspect | StaticResource | DynamicResource |
|--------|----------------|-----------------|
| **Evaluation time** | Once at XAML load | Every time at runtime |
| **Performance** | Fast | Relatively slower |
| **Change reflection** | No | Auto-reflected |
| **Forward reference** | Not available | Available |
| **Use case** | Fixed resources | Theme changes, dynamic resources |
### 4.2 Usage Examples
```xml
```
### 4.3 Theme Switching Implementation
```csharp
namespace MyApp.Services;
using System;
using System.Windows;
public sealed class ThemeService
{
private const string LightThemePath = "/Themes/LightTheme.xaml";
private const string DarkThemePath = "/Themes/DarkTheme.xaml";
///
/// Switch theme
///
public void SwitchTheme(bool isDark)
{
var themePath = isDark ? DarkThemePath : LightThemePath;
var themeUri = new Uri(themePath, UriKind.Relative);
var app = Application.Current;
var mergedDicts = app.Resources.MergedDictionaries;
// Remove existing theme
for (var i = mergedDicts.Count - 1; i >= 0; i--)
{
var dict = mergedDicts[i];
if (dict.Source?.OriginalString.Contains("Theme") == true)
{
mergedDicts.RemoveAt(i);
}
}
// Add new theme
mergedDicts.Add(new ResourceDictionary { Source = themeUri });
}
}
```
---
## 5. Accessing Resources from Code
### 5.1 Resource Lookup
```csharp
namespace MyApp.Helpers;
using System.Windows;
using System.Windows.Media;
public static class ResourceHelper
{
///
/// Find resource (FindResource - throws if not found)
///
public static Brush GetBrush(string key)
{
return (Brush)Application.Current.FindResource(key);
}
///
/// Find resource (TryFindResource - returns null if not found)
///
public static Brush? TryGetBrush(string key)
{
return Application.Current.TryFindResource(key) as Brush;
}
///
/// Find resource from element (searches upward)
///
public static T? FindResource(FrameworkElement element, string key) where T : class
{
return element.TryFindResource(key) as T;
}
}
```
### 5.2 Setting Dynamic Resource
```csharp
// Set DynamicResource from code
button.SetResourceReference(Button.BackgroundProperty, "PrimaryBrush");
// Set StaticResource from code (direct resource assignment)
button.Background = (Brush)FindResource("PrimaryBrush");
```
---
## 6. ComponentResourceKey (For External Libraries)
### 6.1 Definition
```csharp
namespace MyLib.Controls;
using System.Windows;
public static class MyLibResources
{
// Define component resource key
public static readonly ComponentResourceKey PrimaryBrushKey =
new(typeof(MyLibResources), "PrimaryBrush");
public static readonly ComponentResourceKey ButtonStyleKey =
new(typeof(MyLibResources), "ButtonStyle");
}
```
### 6.2 Usage
```xml
```
```xml
```
---
## 7. Resource Lookup Order
```
1. Element's own Resources
2. Parent element Resources (searching upward in Visual Tree)
3. Window/Page Resources
4. Application.Resources
5. Theme resources (Generic.xaml)
6. System resources (SystemColors, SystemFonts)
```
---
## 8. Checklist
- [ ] Define colors as Color type, Brushes in separate file
- [ ] Separate style files per control
- [ ] Use StaticResource for fixed resources, DynamicResource for theme resources
- [ ] Verify ResourceDictionary merge order (dependency order)
- [ ] Inherit common styles with BasedOn
- [ ] Expose library resources with ComponentResourceKey
---
## 9. References
- [Resources Overview - Microsoft Docs](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/systems/xaml-resources-overview)
- [Styles and Templates - Microsoft Docs](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/styles-templates-overview)