Home > Back-end >  WPF XAML, Re-Use a color / solidbrush in ResourceDictionary
WPF XAML, Re-Use a color / solidbrush in ResourceDictionary

Time:12-04

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 toggeld to the main content.

I tried also sth. like

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

put here I get the obvious warning incompatible type.

CodePudding user response:

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

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