Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference a StaticResource in code-behind?

Tags:

winrt-xaml

In XAML I do it like this:

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

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

like image 459
Jerry Nixon Avatar asked Jul 01 '15 16:07

Jerry Nixon


People also ask

How do you declare a static resource in WPF?

To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.


2 Answers

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!

like image 50
Jerry Nixon Avatar answered Oct 04 '22 20:10

Jerry Nixon


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;
like image 27
Josh Bowden Avatar answered Oct 04 '22 20:10

Josh Bowden