Inheriting Style in Silverlight 3

CSS developers are quite familiar with Style Inheritance i.e defining new styles based on existing ones. In Silverlight 3, you can do style inheritance by using BasedOn attribute on Style.

Here’s an example. We will first create two styles (FontSz and FontWt) to style two different buttons as shown below:

<UserControl x:Class="SilverlightSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<
StackPanel x:Name="LayoutRoot" Height="300" Width="300">
<
StackPanel.Resources>
<
ResourceDictionary>
<
Style x:Name="FontSz" TargetType="Button">
<
Setter Property="FontSize" Value="18" />
</
Style>
<
Style x:Name="FontWt" TargetType="Button">
<
Setter Property="FontStyle" Value="Italic"/>
</
Style>
</
ResourceDictionary>
</
StackPanel.Resources>
<
StackPanel>
<
Button Content="Button One" Style="{StaticResource FontSz}"/>
<
Button Content="Button Two" Style="{StaticResource FontWt}"/>
</
StackPanel>
</
StackPanel>
</
UserControl>

The output of this markup will be similar to the following:

Style Inheritance

Now if you want the FontWt style to be based on the FotnSz style, then use the new attribute ‘BasedOn’ as shown below:

<Style x:Name="FontWt" TargetType="Button"
BasedOn="{StaticResource FontSz}">
<
Setter Property="FontStyle" Value="Italic"/>
</
Style>

Now if you run the sample, the output will be as shown below:

Style Inheritance

Observe how Button Two now has two styles – one inherited from FontSz and the other is its own style (FontWt).



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: