WPF: Referencing app-wide resources in code-behind
Asked Answered
A

2

14

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.

Appraise answered 4/2, 2010 at 19:52 Comment(1)
S
29

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

Samantha answered 4/2, 2010 at 20:0 Comment(1)
TryFindResource() may be a better solution as per this answer.Eden
C
3

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.

Chancre answered 26/12, 2014 at 3:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.