[c#] Accessing a resource via codebehind in WPF

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 :)

This question is related to c# wpf xaml resources code-behind

The answer is


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).


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.


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); ;
    }
}

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


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"];

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

{DefaultNamespace}.Properties.Resources.{ResourceName}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to xaml

Setting DataContext in XAML in WPF Change color of Button when Mouse is over Implement Validation for WPF TextBoxes Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to set DataGrid's row Background, based on a property value using data bindings WPF C# button style How to clear a textbox once a button is clicked in WPF? Add Items to Columns in a WPF ListView Binding ConverterParameter

Examples related to resources

Spring Boot access static resources missing scr/main/resources How do I add a resources folder to my Java project in Eclipse Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource Reading a resource file from within jar How to fix the "508 Resource Limit is reached" error in WordPress? How to get absolute path to file in /resources folder of your project getResourceAsStream returns null How to read file from res/raw by name Load image from resources Resource leak: 'in' is never closed

Examples related to code-behind

How to call a C# function from JavaScript? how to access master page control from content page Set Text property of asp:label in Javascript PROPER way ASP.NET Web Application Message Box How to programmatically set the Image source Accessing a resource via codebehind in WPF Adding css class through aspx code behind Passing arguments to JavaScript function from code-behind The name 'controlname' does not exist in the current context ASP.net page without a code behind