#84 – Store Reusable Objects in a Resource Dictionary

Assume that you want to set the background color for two buttons to the same color.  You could specify a SolidColorBrush for each button’s Background property :

 <Button Name="btnOne" Content="Dum" Height="23" Width="75" Click="Button_Click">
         <SolidColorBrush Color="AliceBlue"/>
 <Button Name="btnTwo" Content="Dee" Height="23" Width="75" >
         <SolidColorBrush Color="AliceBlue"/>

In doing this, you created two different brushes.  But you could have been more efficient by creating a single brush, storing it in the resource dictionary of the parent window and then referencing the common brush when specifying the buttons’ Background property :

     <SolidColorBrush x:Key="aliceBrush" Color="AliceBlue"/>
 <StackPanel Name="spContainer">
     <Button Name="btnOne" Background="{StaticResource aliceBrush}" Content="Dum" Height="23" Width="75" Click="Button_Click" />
     <Button Name="btnTwo" Background="{StaticResource aliceBrush}" Content="Dee" Height="23" Width="75" />

We created the common brush in the window’s resource dictionary–specified by the Resources property–and then referred to it in each Button using the StaticResource markup extension and a key.


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #84 – Store Reusable Objects in a Resource Dictionary

  1. Pingback: #148 – Property Values Set Using Expressions Overwrite the Base Value « 2,000 Things You Should Know About WPF

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: