Using a StaticResource SolidColorBrush to define the Gradient Stop Colors

33,564

Solution 1

Ok, I found the problem:

Using Color and not SolidColorBrush..

<Color x:Key="colorbrushMedium">#FF5A5A5A</Color>
<Color x:Key="colorbrushDark">#FF222222</Color>
<LinearGradientBrush>
    <GradientStop Color="{StaticResource colorbrushMedium}"/>
    <GradientStop Color="{StaticResource colorbrushDark}" Offset="1"/>
</LinearGradientBrush>

This seems to solve my problem!

Solution 2

Use Binding to reference the color both in SolidColorBrush and in LinearGradientBrush:

<SolidColorBrush x:Key="stop1" Color="#FF5A5A5A"/>
<SolidColorBrush x:Key="stop2" Color="#FF222222"/>

<LinearGradientBrush x:Key="gradient">
  <GradientStop Color="{Binding Source={StaticResource stop1},Path=Color}" Offset="0"/>
  <GradientStop Color="{Binding Source={StaticResource stop2},Path=Color}" Offset="1"/>
</LinearGradientBrush>
Share:
33,564
code-zoop
Author by

code-zoop

Updated on July 09, 2022

Comments

  • code-zoop
    code-zoop almost 2 years

    I am creating some wpf resource dictionaries with all the styles for an application! I have a few LinearGradientBrushes, where the color is set directly in the LinearGradientBrush reference as GradientStops. However, I want to have a predefined set of colors that I can use a a reference for each GradientStop, so that changing the color scheme for the application is a matter of changing the values of the SolidColorBrushes:

    <SolidColorBrush Color="#5A5A5A" x:Key="colorbrushMedium" /> 
    <SolidColorBrush Color="#222222" x:Key="colorbrushDark" />  
    
    
    <LinearGradientBrush>
        <GradientStop Color="{StaticResource colorbrushMedium}"/>
        <GradientStop Color="{StaticResource colorbrushDark}" Offset="1"/>
    </LinearGradientBrush>
    

    With the code example above, I am getting the following error:

    Cannot convert the value in attribute 'Color' to object of type 'System.Windows.Media.Color'. '#5A5A5A' is not a valid value for property 'Color'.  
    

    The line it refers to is the line where <GradientStop Color="{StaticResource colorbrushMedium}"/> is defined.

    Any ideas?

  • Florian
    Florian almost 12 years
    You can even write the color defined in static class Colors instead of the hex code, e.g. Gray.
  • redtetrahedron
    redtetrahedron over 10 years
    What if you also need to use the same color for properties that require a SolidColorBrush?