89

I have a custom collection defined in my window resources as follows (in a Sketchflow app so the window is actually a UserControl):

<UserControl.Resources>
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</UserControl.Resources>

I want to be able to refer to this collection in the codebehind, which I expected would be by the x:Name, but I can't seem to access it.

I can get a reference to it using

myRef = (MyCollection) this.FindName("myKey");

but this seems hackish. Is this bad practice, and what would be better? Thanks :)

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
randomsequence
  • 1,338
  • 1
  • 11
  • 14

7 Answers7

101

You should use System.Windows.Controls.UserControl's FindResource() or TryFindResource() methods.

Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
japf
  • 6,598
  • 3
  • 33
  • 30
  • 8
    You can use: Application.Current.FindResource(errorColorResourceName) as MyCollection or this.FindResource("RainbowBrush") as MyCollection. It depends on the context. – Tal Segal Oct 27 '16 at 09:24
  • 16
    Can you elaborate on "Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place)." ? Where would such a string constant go that would change the XAML key as well as the C# code behind? – Mike Christiansen Oct 29 '18 at 14:36
  • 1
    +1 for > Can you elaborate on "Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place)." ? Where would such a string constant go that would change the XAML key as well as the C# code behind? – tolache Apr 06 '21 at 10:15
30

You may also use this.Resources["mykey"]. I guess that is not much better than your own suggestion.

Jakob Christensen
  • 14,826
  • 2
  • 51
  • 81
23

Not exactly direct answer, but strongly related:

In case the resources are in a different file - for example ResourceDictionary.xaml

You can simply add x:Class to it:

<ResourceDictionary x:Class="Namespace.NewClassName"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>

And then use it in code behind:

var res = new Namespace.NewClassName();
var col = res["myKey"];
Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79
itsho
  • 4,640
  • 3
  • 46
  • 68
  • 12
    +1, but to be able to find resources using it's key I had to call `res.InitializeComponent()` before attempting to access the key otherwise the object would show no keys and the call to `res["myKey"]` would return null. – Stephen Ross Dec 17 '15 at 10:22
  • Wow that's awesome... I never knew you could do that and it just solved a problem for me quick and easy! I did need to call InitializeComponent() like @StephenRoss said but other than that works like a charm. – sfaust Sep 25 '17 at 19:06
  • A perfect solution to use from `Converters` – Brains May 15 '19 at 08:09
11

If you want to access a resource from some other class (i.g. not a xaml codebehind), you can use

Application.Current.Resources["resourceName"];

from System.Windows namespace.

Raman Sinclair
  • 1,194
  • 17
  • 31
  • This is useful if you need to access the resource from a static constructor or method, and therefore don't have the ability to call `FindResource` or `TryFindResource`. – Steven Rands May 14 '20 at 11:10
9

You can use a resource key like this:

<UserControl.Resources>
    <SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />

public partial class Foo : UserControl
{
    public Foo()
    {
        InitializeComponent();
        var brush = (SolidColorBrush)FindResource(MyKey);
    }

    public static ResourceKey MyKey { get; } = CreateResourceKey();

    private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
    {
        return new ComponentResourceKey(typeof(Foo), caller); ;
    }
}
Johan Larsson
  • 17,112
  • 9
  • 74
  • 88
1

I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below

{DefaultNamespace}.Properties.Resources.{ResourceName}
Ranier Jardim
  • 56
  • 1
  • 5
0

A nice clean example from Microsoft documents makes it simple:

private void myButton_Click(object sender, RoutedEventArgs e)
{
  Button button = (Button)sender;
  button.Background = (Brush)this.FindResource("RainbowBrush");
}
Miyamoto Musashi
  • 502
  • 7
  • 15