#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #810 – Setting Foreground and Background Properties from Code

  1. Pingback: Dew Drop – May 1, 2013 (#1,538) | Alvin Ashcraft's Morning Dew

Leave a comment