#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

Advertisement

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

#221 – Changing a Brush at Run-Time

You can change aspects of a Brush, such as its color, at run-time and any objects that use that brush will automatically be redrawn.

Let’s say that we have several controls in a window that make use of a SolidColorBrush:

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

	<StackPanel>
		<Button Content="Don't Push Me" Background="{StaticResource magicBrush}" Width="120" Margin="10"/>
		<Label Content="Pull my finger!" Foreground="{StaticResource magicBrush}" HorizontalAlignment="Center"/>
		<Ellipse Height="100" Width="200" Fill="{StaticResource magicBrush}" Margin="10"/>
	</StackPanel>

.

Now assume that we change the Color property of the brush at run-time:

    SolidColorBrush magicBrush = (SolidColorBrush)this.Resources["magicBrush"];
    magicBrush.Color = Colors.Purple;

When you do this, you’ll notice that the color in all of the controls changes as soon as this code executes.

All of the controls update immediately because SolidColorBrush derives from Freezable, which supports the Changed event.  The Changed event fires when the color changes and the controls handle that event and redraw themselves.

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