Blogger news

Blogger templates

Tuesday, February 22, 2011

Resource Dictionary in Silverlight 4.0 and Windows Phone

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,

Click ok. Now you get a window like below,
Click ok .

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,

3. Add your style information to the resource dictionary as below,



<Style x:Key="Heading1" TargetType="TextBlock">
<Setter Property="FontSize" Value="22" />
<Setter Property="Foreground" Value="Silver" />
<Style x:Key="Heading2" TargetType="TextBlock">
<Setter Property="FontSize" Value="18" />

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,

<ResourceDictionary Source="ResourceDictionary.xaml"/>

5. Add two TextBlock inside main grid and apply styles as below,

<Grid x:Name="LayoutRoot" Background="White">
<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}" />

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:

Kiran said...

Simple and good.. Thankyou

Post a Comment