Search code examples
wpfxaml

WPF XAML, Re-Use a color / solidbrush in ResourceDictionary


I have some colors in my WPF C# app, which I want to re-use. To avoid double typing (and maintaining issues).

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <SolidColorBrush x:Key="mybackground">#ffffff</SolidColorBrush>
    <SolidColorBrush x:Key="myforeground">#000000</SolidColorBrush>

    <SolidColorBrush x:Key="HeaderBackground">#000000</SolidColorBrush>
    <SolidColorBrush x:Key="HeaderForeground">#ffffff</SolidColorBrush>
    
</ResourceDictionary>

how can I re-use the mybackground or myforeground in other brushes?

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <SolidColorBrush x:Key="mybackground">#ffffff</SolidColorBrush>
    <SolidColorBrush x:Key="myforeground">#000000</SolidColorBrush>

    <SolidColorBrush x:Key="HeaderBackground">{StaticResource myforeground}/SolidColorBrush>
    <SolidColorBrush x:Key="HeaderForeground">{StaticResource mybackground}/SolidColorBrush>
    
</ResourceDictionary>

HINT: The header use the fore- and background color toggled to the main content.

I tried also something like:

    <SolidColorBrush x:Key="HeaderBackground" Color="{StaticResource myforeground}"></SolidColorBrush>
    <SolidColorBrush x:Key="HeaderForeground" Color="{StaticResource mybackground}"></SolidColorBrush>

But here I get the obvious warning incompatible type.


Solution

  • if you want to reuse colors, define Color as resource:

    <Color x:Key="red">#FF0000</Color>
    <SolidColorBrush x:Key="ErrorBrush" Color="{StaticResource red}"/>