#810 – Setting Foreground and Background Properties from Code

You can set both the Foreground and Background properties at run-time, from code.  Recall that both properties are set to an instance of a Brush, which can be a SolidColorBrush,  one of the GradientBrush subtypes, or one of several other different types of Brush objects.

The simplest way to change a Foreground or Background property, assuming that you want to set them to a solid color, is to set the property to refer to one of the preexisting SolidColorBrush objects that are part of the Brushes class.

The Brushes class includes a set of static SolidColorBrush objects, each representing one of the standard predefined colors.

        <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"/>

810-001

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Set to one of the predefined brushes
            lblMA.Background = Brushes.Plum;
        }

810-002