Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Referencing app-wide resources in code-behind

I have made my own custom converter which given a string returns a Brush. Now I'm able to return constant brushes such as Brushes.Red etc., but I really want to use my own colors which I have defined in an application-wide resource.

How do I reference application-wide resources from my own custom converter class? I'd use FindResource but as I said, this is from my own converter class, not a window or control.

like image 987
Deniz Dogan Avatar asked Feb 04 '10 19:02

Deniz Dogan


People also ask

What is code behind in WPF?

Code-behind is a term used to describe the code that is joined with markup-defined objects, when a XAML page is markup-compiled. This topic describes requirements for code-behind as well as an alternative inline code mechanism for code in XAML.

What is dynamic resource in WPF?

Dynamic ResourceThe concept is the same as data binding in WPF if the value of the bound property is changed. So is the value on UI. Change XAML as follows: added a new button. <Window x:Class="A.MainWindow"

How do you reference a resource dictionary?

You can reference a resource throughout an app or from any XAML page within it. You can define your resources using a ResourceDictionary element from the Windows Runtime XAML. Then, you can reference your resources by using a StaticResource markup extension or ThemeResource markup extension.


2 Answers

If these are defined on your Application, you can use Application.Current.FindResource() to find them by name.

like image 104
Reed Copsey Avatar answered Sep 22 '22 02:09

Reed Copsey


Adding to Reed's answer, if your resource dictionary is a standalone XAML file, you need to ensure it is (as Reed says) "defined on your Application."

App.xaml:

<Application x:Class="WpfApplication10.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary Source="Dictionary1.xaml" />
    </Application.Resources>
</Application>

Dictionary1.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TextBlock x:Key="k_foo" Text="FOO" />
</ResourceDictionary>

The Build Action on this dictionary XAML file can be set to Page. It should be in the same directory as the App.xaml file.

like image 21
Glenn Slayden Avatar answered Sep 21 '22 02:09

Glenn Slayden