#222 – Example: Changing a Color Using RGB Sliders

Here’s an example of changing a color at run-time, using three sliders.

The XAML defines a control and three sliders:

	<Window.Resources>
		<SolidColorBrush x:Key="magicBrush" Color="Red"/>
	</Window.Resources>

	<StackPanel>
		<Ellipse Height="100" Width="200" Fill="{StaticResource magicBrush}" Margin="30"/>

		<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
			<Label Content="Red" VerticalAlignment="Center"/>
        	<Slider Name="sliR" Width="150" Margin="10" Minimum="0" Maximum="255" TickFrequency="1" IsSnapToTickEnabled="True"
				Value="255"
				ValueChanged="sli_ValueChanged"/>
			<Label Content="{Binding ElementName=sliR, Path=Value}" VerticalAlignment="Center"/>
		</StackPanel>
		<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
			<Label Content="Green" VerticalAlignment="Center"/>
        	<Slider Name="sliG" Width="150" Margin="10" Minimum="0" Maximum="255" TickFrequency="1" IsSnapToTickEnabled="True"
				ValueChanged="sli_ValueChanged"/>
			<Label Content="{Binding ElementName=sliG, Path=Value}" VerticalAlignment="Center"/>
		</StackPanel>
		<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
			<Label Content="Blue" VerticalAlignment="Center"/>
        	<Slider Name="sliB" Width="150" Margin="10" Minimum="0" Maximum="255" TickFrequency="1" IsSnapToTickEnabled="True"
				ValueChanged="sli_ValueChanged"/>
			<Label Content="{Binding ElementName=sliB, Path=Value}" VerticalAlignment="Center"/>
		</StackPanel>
	</StackPanel>

In code, we have a single method that executes when the sliders change, which changes the brush color:

        private void sli_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
        {
			SolidColorBrush magicBrush = (SolidColorBrush)this.Resources["magicBrush"];

            if ((sliR != null) && (sliG != null) && (sliB != null))
            {
                magicBrush.Color = Color.FromRgb((byte)sliR.Value, (byte)sliG.Value, (byte)sliB.Value);
            }
        }

#211 – Creating a Color Value in Code

Color, defined in System.Windows.Media, is a structure that represents a color by storing Red (R), Green (G) and Blue (B) values as well as an Alpha (A) value indicating opacity.

You can create a color value in code using the Color.FromRgb and Color.FromArgb static methods.

The Color.FromRgb method takes three parameters, allowing you specify the R, G and B components of the color, each of which is in the range 0-255.

            Color lightGreen = Color.FromRgb(120, 255, 0);
            this.Background = new SolidColorBrush(lightGreen);

The Color.FromArgb method also takes a parameter representing the alpha channel (0-255), which dictates the opacity of the color.  A value of 255 represents a fully opaque color and a value of 0 represents a fully transparent color.

            // Set window background to semi-transparent color
            Color lightGreen = Color.FromArgb(50, 120, 255, 0);
            this.Background = new SolidColorBrush(lightGreen);

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

    <Window.Background>
        <SolidColorBrush Color="PowderBlue"/>
    </Window.Background>

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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="346" Width="590"
        Background="PowderBlue">

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.

#208 – Color Values Are Stored as RGB Values

Although we can specify colors for brushes in WPF using predefined names, e.g. “DarkBlue”, each color is actually stored as an RGB (Red/Green/Blue) value.

For example, if we specify a color as “Lavender” and then look at the Color property of the SolidColorBrush at runtime, we see that the color is actually a structure containing a number of fields.

The main fields in this structure are the R, G, and B fields, which specify Red, Green and Blue values that make up the resulting color.  Each value has a range from 0-255.  So “Lavender” is: R=230, G=230, B=250.

The A field represents the alpha channel (also 0-255), which dictates that transparency of the object (0 = fully transparent, 255 = fully opaque).

The ScA, ScR, ScG, and ScB properties allowing reading or writing the color in the scRGB format.

#207 – Setting a Control’s Background Color

The Control class is a base class for all user interface elements that a user interacts with.  (This includes the Window class).

Control includes a Background property that you can set to cause the background of the control to be filled in, or colored.

Background’s type is System.Windows.Media.Brush, which means that you specify not just a background color, but an instance of a Brush object.

There are several kinds of brushes, but the most common is the SolidColorBrush, which allows setting the background to a solid color.

In the example below, we set the background color of a Window to the color PowderBlue.

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Background>
        <SolidColorBrush Color="PowderBlue"/>
    </Window.Background>
    <Grid>
        <Label Content="Hi!"/>
    </Grid>
</Window>

Here’s the result:

Here are some other examples of setting the Background property for various controls:

Follow

Get every new post delivered to your Inbox.

Join 129 other followers