#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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: