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.
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"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="RoundButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Width="100" Height="100" Margin="5">
<Ellipse Fill="#FF6DB4EF"/>
<Ellipse>
<Ellipse.Fill>
<RadialGradientBrush>
<GradientStop Offset="0" Color="#00000000"/>
<GradientStop Offset="0.88" Color="#00000000"/>
<GradientStop Offset="1" Color="#80000000"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Margin="10">
<Ellipse.Fill>
<LinearGradientBrush>
<GradientStop Offset="0" Color="#50FFFFFF"/>
<GradientStop Offset="0.5" Color="#00FFFFFF"/>
<GradientStop Offset="1" Color="#50FFFFFF"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="Resources/MyResourceDictionary.xaml">
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Button x:Name="btnRound" Style="{DynamicResource RoundButtonStyle}" />
</Grid>
</UserControl>
ScreenShot
No comments:
Post a Comment