#212 – Creating a Linear Gradient Brush

Whenever WPF expects a Brush, e.g. for a control’s Background property, you can use a linear gradient brush rather than a solid color brush.

A linear gradient is a fill style that fills an area with a pattern that starts out as one color and gradually changes to one or more other colors.

A linear gradient changes colors along a gradient line.  By default, this line extends from the upper left corner down to the lower right corner of the area being filled.

You specify the colors to be used by defining a series of gradient stops.  Each stop describes the color to use and an offset (0.0 to 1.0) indicating how far along the gradient line that color will appear.

Here’s an example, with the gradient changing from red to blue.

        <Button Height="100" Width="200" Content="A button" Margin="10">
            <Button.Background>
                <LinearGradientBrush>
                    <GradientStop Color="Red" Offset="0.0"/>
                    <GradientStop Color="Blue" Offset="1.0"/>
                </LinearGradientBrush>
            </Button.Background>
        </Button>

Advertisement