WPF How to use Resource Dictionary in XAML

In this article, we will learn how we can use merge a resource dictionary in WPF XAML.

As we all know, that WPF applications supports rich media and graphics support, styles and templates should be managed in such a way that they can be reused. Styles can be defined in the same XAML file or all the styles and templates which are reusable across different screens can be accumulated in a Resource Dictionary File. 

What is Resource Dictionary?

In Resource Dictionary, one can write reusable styles, DataTemplates, ControlTemplates. One can also define custom definitions for Brush, Color, Background etc.

Each of these custom defined style or template is called as resource and a unique key must be given to each resource.

Steps to add Resource Dictionary

1)      Select a folder in Solution Explorer.

2)      Right click and select “Add”.

3)      Click on “Resource Dictionary” menu item.

4)      A New Item Wizard Popup will open with Resource Dictionary Item template selected. One can rename the item.
      Add Resource Dictionary Screenshot

Resource Dictionary Example
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    <Style x:Key="RoundButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Template">
                    <Grid Width="100" Height="100" Margin="5">
                        <Ellipse Fill="#FF6DB4EF"/>
                                    <GradientStop Offset="0" Color="#00000000"/>
                                    <GradientStop Offset="0.88" Color="#00000000"/>
                                    <GradientStop Offset="1" Color="#80000000"/>
                        <Ellipse Margin="10">
                                    <GradientStop Offset="0" Color="#50FFFFFF"/>
                                    <GradientStop Offset="0.5" Color="#00FFFFFF"/>
                                    <GradientStop Offset="1" Color="#50FFFFFF"/>

Code Snippet

In the below section, there is a code snippet of how we can a resource dictionary in a XAML file. Since we can have a resource dictionary for each control, we are going to merge the other resource files to the existing resource dictionary.
<UserControl x:Class="WPF_Sample_Project_Test.ResourceDictionaryExample"
             d:DesignHeight="300" d:DesignWidth="300">

        <Button x:Name="btnRound" Style="{DynamicResource RoundButtonStyle}" />



No comments:

Post a Comment