#210 – Specifying Colors in XAML As RGB Values

The type converter that converters names of colors to a SolidColorBrush of the specified color will also create a brush of a specified RGB color.  You can specify RGB color values in XAML in one of several ways.

In the example below, we specify each of the R, G and B values as a 2 hex-digit number (00-FF), representing the range 0-255.  The digits are ordered RRGGBB, so the value #FF0000 is solid red.

        <Button Height="25" Width="100" Content="A button" Background="#FF0000"/>

Here are some other formats that you can use:

  • #rgb – RGB value with only 1 digit per color (0-F).  E.g. #FF0 (Red+Green = Yellow)
  • #argb – single-digit RGB + alpha value (0-F)
  • #aarrggbb – 2 digits for R, G, B + 2 digits for alpha channel (transparency)
  • sc#scA,scR,scG,scB – scRGB formatted number, each value ranging from 0.0 to 1.0

#209 – Specifying a Color Where a Brush Is Expected in XAML

We saw earlier how to set the Background property for a control in XAML, by setting the property to an instance of a SolidColorBrush and then setting the Color property for the brush:

        <SolidColorBrush Color="PowderBlue"/>

We can be much more concise than this, however, just setting the value of the Background property directly to a color:

<Window x:Class="WpfApplication2.MainWindow"
        Title="MainWindow" Height="346" Width="590"

This works through the use of type converters.  The Background property uses a type converter to convert a string to an instance of a SolidColorBrush of the corresponding color.  Specifically, it sets the property to point to the preexisting Brushes.PowderBlue brush.  You can see the full list of predefined brushes here.

#172 – Changes to a Brush Cascade to Consumers of the Brush

If you create a Brush object, in XAML or code, and use that Brush in some controls, any changes to the original Brush are automatically reflected in controls that use the brush.

For example, assume that we define a teal SolidColorBrush as a resource and use it to render a Label.

        <SolidColorBrush x:Key="tealBrush" Color="Teal"/>
        <Label Content="I'm teal!" Foreground="{StaticResource tealBrush}"/>

Now assume that we change the brush’s color at runtime:

            SolidColorBrush theBrush = (SolidColorBrush)this.Resources["tealBrush"];
            theBrush.Color = Colors.DarkMagenta;

You’ll see that the foreground color of the Label changes immediately, as soon as we change the color of the brush.

This change notification behavior is true not only of the Brush class, but of all other classes used in rendering WPF graphics.