XAML 101: Colors and SolidColorBrush


Source code for this sample on GitHub: https://github.com/billreiss/xamlnative/tree/master/Xaml101/006_SolidColorBrush

Create a new “Universal Blank App” project, or use the HelloXaml project we created earlier. In MainPage.xaml, change the Grid to look like this:

<Grid Background="Red">

When we run this, we just get a red background for the page:


Looks pretty simple, but there is a bit more going on behind the scenes, and the UWP framework does some things for us to help out. First of all, Red is a predefined color. There are many of these, and it can be easier and more descriptive than specifying a hex value. That being said, this is equivalent to what’s above:

<Grid Background="#FFFF0000">

The first “FF” is the transparency value, and a value of “FF” is fully opaque. The the other pairs are red, green, and blue respectively. So we have full red, and no green or blue. The transparency value is optional if you want no transparency, so this is also equivalent:

<Grid Background="#FF0000">


Now if you look at the definition of the Grid.Background property, it looks like this:


So we see that Background is of type Brush, and not Color. Most places in XAML that take a color (backgrounds, border colors, foregrounds) are of type Brush. When a color is specified for Background, like Red, this value is converted automatically to a SolidColorBrush for you, so that you don’t have to use the longer form of specifying a SolidColorBrush of type Red, but we can do that:

        <SolidColorBrush Color="Red"/>

And this is exactly the same when it is drawn.

There are some more interesting brushes available and in the next post we will look at another of these, the LinearGradientBrush.