#811 – Setting Color Values in Code Based on System Colors

You can set the Foreground or Background properties of a control to a brush that will render the control using one of the predefined system colors.  The SystemColors class contains a number of static SolidColorBrush objects representing brushes that match the system colors.

811-001

        <Label Name="lblMA" Content="Margaret Atwood" HorizontalAlignment="Center"
               Padding="20,10" Margin="10"
               Background="LightPink"/>
        <Button Content="Change Color" HorizontalAlignment="Center"
                Padding="10,5" Click="Button_Click"/>

 

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Set to one of the predefined brushes that map
            // to the system colors
            lblMA.Background = SystemColors.ActiveCaptionBrush;
        }

811-002
811-003

#225 – Using a Brush that Will Update When a System Color Changes

The System.Windows.SystemColors class contains a series of static properties that expose the current predefined system colors.  (Click here to see a list of these system colors).

If you use one of these predefined system colors as a brush using the x:Static markup extension, the color used will be the value of that system color at the time that the application started.  If the system color changes while the application is running, the brush will not change.

You can create and use a dynamic brush, which will change whenever the system color changes, as follows:

	<StackPanel>
		<Ellipse Height="100" Width="200" Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" Margin="30"/>
	</StackPanel>

Notice that we use the XxxBrushKey property, rather than the XxxBrush property.  Both properties give us a brush, but the XxxBrushKey property gives us a dynamic brush that will change when the system color changes.

#223 – Predefined System Colors

The System.Windows.SystemColors class contains a series of static properties that expose the current predefined system colors.  These are the predefined system colors that you can change from the Control Panel (Control Panel\Appearance and Personalization\Personalization\Window Color and Appearance in Windows 7).

The properties come in triplets.  For each system color Xxx, there are XxxBrush, XxxBrushKey and XxxColor properties.

Here’s a chart showing the default colors, under the Aero theme in Windows 7.  (Click on the image to see it full-sized).

Follow

Get every new post delivered to your Inbox.

Join 356 other followers