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.

Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162

2 Answers2

29

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

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • `TryFindResource()` may be a better solution as per [this answer](https://stackoverflow.com/a/37955433/4465708). – z33k Sep 17 '21 at 11:00
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.

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108