WPF SolidColorBrush

This article demonstrates how to use SolidColorBrush in WPF using XAML and C#.


Solid Brush in WPF

A solid brush is the most basic brush and paints an area with a solid color.  The SolidColorBrush object represents a solid color brush. The Opacity property of the SolidColorBrush represents the transparency of the color that values between 0 and 1 where 0 is fully transparent and 1 is fully opaque. The Color property represents the solid color of the brush, which is a type of Colors class.

Creating a Solid Brush

The SolidColorBrush element in XAML creates a brush with a solid color. The following code snippet creates a solid color brush with a blue color.

<SolidColorBrush Color="Blue" />

We can also set the Color property to the hexadecimal code of the color. The following code snippet sets the color of the SolidColorBrush to blue using the hexadecimal value of blue color.

<SolidColorBrush Color="#FF0000FF" />

Figure 13 taken from MSDN shows the properties and hexadecimal values of the properties of the Colors class.

SolidColorBrushImg1.jpg

Figure 13. Colors class properties

As we have seen in the previous sections, the Fill property of shape paints the internal areas of a shape. We can direct specify a color in the Fill property and the default brush used to fill a shape is solid brush. The code snippet in Listing 12 creates a rectangle shape sets the Fill property to Blue.

<Rectangle

    Width="200"

    Height="100"

    Stroke="Black"

    StrokeThickness="4"

    Fill="Blue">

</Rectangle>

Listing 12

The output looks like Figure 14.

SolidColorBrushImg2.jpg 

Figure 14. A shape filled with a solid color

We can simply replace Listing 12 with the Listing 13 where we set Rectangle.Fill property to a SolidColorBrush with a blue color.

<Rectangle

    Width="200"

    Height="100"

    Stroke="Black"

    StrokeThickness="4">

    <Rectangle.Fill>

        <SolidColorBrush Color="Blue" />

    </Rectangle.Fill>

</Rectangle>

Listing 13

The CreateARectangleWithSolidBrush method listed in Listing 14 draws same rectangle in Figure 13 dynamically.

/// <summary>

/// Creates a blue rectangle with black border

/// </summary>

public void CreateARectangleWithSolidBrush()

{

    // Create a Rectangle

    Rectangle blueRectangle = new Rectangle();

    blueRectangle.Height = 100;

    blueRectangle.Width = 200;

 

    // Create a blue and a black Brush

    SolidColorBrush blueBrush = new SolidColorBrush();

    blueBrush.Color = Colors.Blue;

    SolidColorBrush blackBrush = new SolidColorBrush();

    blackBrush.Color = Colors.Black;

 

    // Set Rectangle's width and color

    blueRectangle.StrokeThickness = 4;

    blueRectangle.Stroke = blackBrush;

    // Fill rectangle with blue color

    blueRectangle.Fill = blueBrush;

 

    // Add Rectangle to the Grid.

    LayoutRoot.Children.Add(blueRectangle);

}

Listing 14