#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">
     <Button.Background>
         <SolidColorBrush Color="AliceBlue"/>
     </Button.Background>
 </Button>
 <Button Name="btnTwo" Content="Dee" Height="23" Width="75" >
     <Button.Background>
         <SolidColorBrush Color="AliceBlue"/>
     </Button.Background>
 </Button>

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 :

 <Window.Resources>
     <SolidColorBrush x:Key="aliceBrush" Color="AliceBlue"/>
 </Window.Resources>
 <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" />
 </StackPanel>

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.

Advertisements

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

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 )

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: