Setting the Style property of a WPF Label in code?

Solution 1:

Where in code are you trying to get the style? Code behind?

You should write this:

If you're in code-behind:

Style style = this.FindResource("LabelTemplate") as Style;
label1.Style = style;

If you're somewhere else

Style style = Application.Current.FindResource("LabelTemplate") as Style;
label1.Style = style;

Bottom note: don't name a Style with the keyword Template, you'll eventually end up confusing a Style and a Template, and you shouldn't as those are two different concepts.

Solution 2:

Please check for null style result or you will be sad... ... if (style != null) this.Style = style;