Showing posts with label Resource Dictionary. Show all posts
Showing posts with label Resource Dictionary. Show all posts

WPF How to use Resource Dictionary in C#



To know what is Resource Dictionary,example of Resource dictionary, how we can add Resource Dictionary and how we can use it from XAML visit here:

Now there may be a case where we need to access a resource dictionary that we have defined in our project, from C# code.
If we have already merged our resource dictionary in XAML, it is easy to access the inner resources using thecontrol.FindResource("<<ResourceKey>>"); method.
 But, if we haven’t merged the resources in XAML and we still need to use the resource dictionary, we have options to use it directly inC# code. 
We have modified the example given here WPF How to use Resource Dictionary in XAML. where we were using ResourceDictionary from XAML.
Below is the XAML and code snippet:
XAML Code:
<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">
        <Grid>
        <Button x:Name="btnRound"  />
    </Grid> 
</UserControl>
C# Code:

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