#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);