How do I reference a StaticResource in code-behind?
Asked Answered
D

5

44

In XAML I do it like this:

<Button Style="{StaticResource NavigationBackButtonNormalStyle}" />

How do I do the same thing in code-behind?

Digestif answered 1/7, 2015 at 16:4 Comment(0)
D
60

The page-level Resources object has the ability to find local, app-level, static, and theme resources. This means you simply do this:

foo2.Style = this.Resources["NavigationBackButtonNormalStyle"] as Style;

Best of luck!

Digestif answered 1/7, 2015 at 16:4 Comment(3)
How to do it just for background color? XAML: <ContentPage.Resources><ResourceDictionary><Color x:Key="Accent">#100c00</Color></ResourceDictionary></ContentPage.Resources> xaml.CS: btnLogout.BackgroundColor = this.Resources["Accent"] as BackgroundColor; result in editor error > the type or namespace BackgroundColor does not exist...Predacious
There's no such thing as "BackgroundColor " in "XAML", you must use "Background" for that purpose. @PredaciousAnatolio
Got null as @Josh Bowden explains in his answer. I recommend that instead of this.Gauger
D
24

During design-time, it seems that trying to resolve a "system resource" using Resources[key] will fail to find the resource and will return null. For example, to get the base Style for a TextBox using Resources[typeof(TextBox)] will return null.

Instead, use TryFindResource(key) since this will first try Resources[key] and then will otherwise try searching through the "system resources" and will return what you're looking for (as per MSDN and Reference Source).

In other words, try this instead:

var style = Application.Current.TryFindResource(key) as Style;
Diazotize answered 21/6, 2016 at 22:12 Comment(1)
This is for WPF only - doesn't exist for XamarinIrresolute
J
16

Try with this

Application.Current.Resources["key"]
Jarrod answered 26/5, 2020 at 13:34 Comment(2)
What are the benefits of your approach over the established answers on this thread?Homothermal
@JeremyCaney local Resources don't contain StaticResources for me.Transparency
N
3

Here's a generic helper class that can be used. The advantage of going this route, is tha tyou will be able to use the same helper to get other types of resources (like Brushes, or DataTemplate for example)

public static class Helper
{
    public static T Get<T>(string resourceName) where T : class
    {
        return Application.Current.TryFindResource(resourceName) as T;
    }
}

And how you would use in code:

yourButton.Style = Helper.Get<Style>("NavigationBackButtonNormalStyle");

And if you wanted to get a brush resource you'd use

ItemTemplate = Helper.Get<DataTemplate>("MyDataTemplate");
Ng answered 13/4, 2018 at 15:44 Comment(0)
O
0

If you are working in the ViewModel, you wont be able to use the answer above.

To bring up to date the answer from Eternal21, you could so this:

public static T Get<T>(string resourceName) 
{   
    try
    {
        var success = Application.Current.Resources.TryGetValue(resourceName, out var outValue);

        if(success && outValue is T)
        {
            return (T)outValue;
        }
        else
        {
            return default(T);
        }
    }
    catch
    {
        return default(T);
    }
}

Note the where clause is missing here. I didn't want to restrict it to classes, so I could use it with Color too which is a struct... so removed it.

Ottavia answered 26/9, 2020 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.