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

Advertisement