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

Advertisements