SolidColorBrush in Silverlight


This article demonstrates how to use a solid brush in Silverlight using XAML and C#.

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 1 taken from MSDN shows the properties and hexadecimal values of the properties of the Colors class.

Figure 1

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 1 creates a rectangle shape sets the Fill property to Blue.

<Rectangle

    Width="200"

    Height="100"

    Stroke="Black"

    StrokeThickness="4"

    Fill="Blue">

</Rectangle>

Listing 1

 

The output looks like Figure 2.

 

Figure 2

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 2

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 3

Summary

In this article, we saw how to create and use a solid color brush in Silverlight using C# and XAML.

 

Up Next
    Ebook Download
    View all
    Learn
    View all