A new feature as of Silverlight 4 is the ability to place your style definitions in external files called Merged Resource Dictionaries. You can write styles in document or application level. If defining in the application level, your styles must be placed in the App.xaml file. This can result in a very large App.xaml. In Silverlight 4, you can now place your style definitions in external files and simply reference them in your application. An additional benefit from this change is that you can now create styles that can be easily reused between your applications, by simply copying the style resource files to your new solution.
Let’s start with example,
1. Open Visual studio for New Silverlight application. Click image below,


2. You can add a Resource Dictionary to a Silverlight application in Visual Studio by right-clicking on your project in the Solution Explorer and selecting Add New Item. On the Add New Item screen select the template named Silverlight Resource Dictionary and enter a name for the dictionary. Click image below,

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="Heading1" TargetType="TextBlock">
<Setter Property="FontSize" Value="22" />
<Setter Property="Foreground" Value="Silver" />
Style>
<Style x:Key="Heading2" TargetType="TextBlock">
<Setter Property="FontSize" Value="18" />
Style>
ResourceDictionary>
Finally, to use the resource dictionary in your application, you need to add an entry in the
ResourceDictionary.MergedDictionaries section, as shown in the following code. Once you have added the entry for the ResourceDictionary, you can then use the styles as normal.
4. Open MainPage.XAML and add the code below just above Grid,
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResourceDictionary.xaml"/>
ResourceDictionary.MergedDictionaries>
ResourceDictionary>
UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
Grid.RowDefinitions>
<TextBlock Text="Heading 1" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource Heading1}" />
<TextBlock Text="Heading 2" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource Heading2}" />
Grid>
6. Run application. You can see two different styles for two heading means styles are fetching from the ResourceDictionary.
Style="{StaticResource Heading1}" this is the tag we apply style. we have give "StaticResource" property to apply style from resource dictionary.
Click image for description and full XAML code,

1 comment:
Simple and good.. Thankyou
Post a Comment