How do I reference a StaticResource in code-behind?

此生再无相见时 提交于 2020-01-14 07:12:20

问题


In XAML I do it like this:

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

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


回答1:


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!




回答2:


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;



回答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");


来源:https://stackoverflow.com/questions/31166428/how-do-i-reference-a-staticresource-in-code-behind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!