Search code examples
wpfstylesfilllineargradientbrush

How Do I convert LinearGradientBrush object to a Style?


What is the XAML Style equivalent of

LinearGradientBrush(Color.FromArgb(255, 154, 153, 153), Color.FromArgb(255, 51, 50, 50), 80)

Ideally, I would like to make an Application Resource that I could reuse. Thanks!


Solution

  • You can use this Xaml...

        <LinearGradientBrush x:Key="MyDefaultBackground" StartPoint="0,0" EndPoint="0,1">
            <GradientStop Offset="0" Color="#ff9a9999"/>
            <GradientStop Offset="1" Color="#ff333232"/>
        </LinearGradientBrush>
    

    This sets a resource called "MyDefaultBackground" for the colours you gave in your question. The start/stop values create a gradient where it's light grey at the top and dark grey at the bottom. You can adjust the start/stop values for a different effect.

    The color stop values are in hex (i.e., 153 decimal is 9a hex), when you need to translate decimal values, you can use the built-in windows calculator in 'programmer mode'.

    Anytime you want to use it where the Style calls for a Brush, you can compose...

    Background={StaticResource MyDefaultBrush}
    

    This will work when the brush is declared higher in the object graph than the style you are composing.

    The MSDN docs for LinearGradientBrush are at http://msdn.microsoft.com/en-us/library/system.windows.media.lineargradientbrush(v=vs.110).aspx