#229 – Using a Gradient Brush for a Window’s Border

The Window class has BorderBrush and BorderThickness properties that allow creating a thick border around the window’s client area.  (Just inside the standard window chrome).

You can use any brush you like as a border brush.  In the example below, we use a linear gradient brush that starts in the upper left corner of the window and cycles through the colors of the rainbow until it reaches the lower right corner of the window.  Note that we set the BorderThickness to 10.

<Window
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	mc:Ignorable="d"
	xmlns:local="clr-namespace:WpfApplication1"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    x:Class="WpfApplication1.MainWindow"
	x:Name="Window"
	Title="Rainbow Border"
	BorderThickness="10">

	<Window.BorderBrush>
		<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
		    <GradientStop Color="Red" Offset="0.0"/>
		    <GradientStop Color="Orange" Offset="0.17"/>
		    <GradientStop Color="Yellow" Offset="0.33"/>
		    <GradientStop Color="Green" Offset="0.5"/>
		    <GradientStop Color="Blue" Offset="0.67"/>
		    <GradientStop Color="Indigo" Offset="0.83"/>
		    <GradientStop Color="Violet" Offset="1.0"/>
		</LinearGradientBrush>
	</Window.BorderBrush>

	<StackPanel VerticalAlignment="Center">
		<Button Content="Click Me" Width="100" Margin="10"/>
		<Label Content="I'm a label, you know" HorizontalAlignment="Center" Margin="10"/>
	</StackPanel>
</Window>

Advertisement

#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>