Posted by: Zeeshan Amjad | December 28, 2009

Style Inheritance


We can create style on the basis of existing style. Style class has one property based on and we can inherited the new style from existing one using this property. Here is a class diagram of Style class.

StyleClass

Here is one XAML file to show the implementation of Style inheritance.

  1: <Window x:Class="WpfStyle.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     Title="Style Inheritance" Height="300" Width="300">
  5:     <Window.Resources>
  6:         <Style x:Key="ParentStyle" TargetType="Button">
  7:             <Setter Property="Margin" Value="5"/>
  8:             <Setter Property="FontSize" Value="16"/>
  9:         </Style>
 10:         <Style x:Key="ChildStyle" TargetType="Button" BasedOn="{StaticResource ParentStyle}">
 11:             <Setter Property="Background" Value="Wheat"/>
 12:             <Setter Property="Foreground" Value="Blue"/>
 13:         </Style>
 14:         <Style x:Key="GrandChildStyle" TargetType="Button" BasedOn="{StaticResource ChildStyle}">
 15:             <Setter Property="FontWeight" Value="Bold"/>
 16:             <Setter Property="Background">
 17:                 <Setter.Value>
 18:                     <LinearGradientBrush>
 19:                         <GradientStop Offset="0" Color="LightYellow"/>
 20:                         <GradientStop Offset="1" Color="Yellow"/>
 21:                     </LinearGradientBrush>
 22:                 </Setter.Value>
 23:             </Setter>
 24:         </Style>
 25:     </Window.Resources>
 26:     <StackPanel>
 27:         <Button Style="{StaticResource ParentStyle}" Name="btn1">Button 1</Button>
 28:         <Button Style="{StaticResource ParentStyle}" Name="btn2">Button 2</Button>
 29:         <Button Style="{StaticResource ChildStyle}" Name="btn3">Button 3</Button>
 30:         <Button Style="{StaticResource ChildStyle}" Name="btn4">Button 4</Button>
 31:         <Button Style="{StaticResource GrandChildStyle}" Name="btn5">Button 5</Button>
 32:         <Button Style="{StaticResource GrandChildStyle}" Name="btn6">Button 6</Button>
 33:     </StackPanel>
 34: </Window>
 35: 

Here we are creating three styles. Here is a block diagram to represent the relationship between these styles.

StyleInheritance

And here is the output of this program

StyleInheritanceOutput

Advertisements

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

Categories

%d bloggers like this: