Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the Style property of a WPF Label in code?

In App.xaml, I have the following code:

<Application.Resources>     <Style x:Key="LabelTemplate" TargetType="{x:Type Label}">         <Setter Property="Height" Value="53" />         <Setter Property="Width" Value="130" />         <Setter Property="HorizontalAlignment" Value="Left" />         <Setter Property="Margin" Value="99,71,0,0" />         <Setter Property="VerticalAlignment" Value= "Top" />         <Setter Property="Foreground" Value="#FFE75959" />         <Setter Property="FontFamily" Value="Calibri" />         <Setter Property="FontSize" Value="40" />     </Style> </Application.Resources> 

This is meant to provide a generic template for my labels.

In the main XAML code, I have the following line of code:

<Label Content="Movies" Style="{StaticResource LabelTemplate}" Name="label1" /> 

However, I'd like to initialize the Style property through code. I have tried:

label1.Style = new Style("{StaticResource LabelTemplate}"); 

and

label1.Style = "{StaticResource LabelTemplate}"; 

Neither solution was valid.

Any help would be appreciated :).

like image 225
Daniel Avatar asked May 21 '12 14:05

Daniel


People also ask

Can we use CSS in WPF?

The only concept for which there really is no correspondent in WPF is CSS class. This can easily be introduced via an attached property.

What is a style in WPF?

Styles provide us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only default behavior of a control can be specified.

How do you style XAML?

A fast way to apply styles to your controls is to right-click on a control on the Microsoft Visual Studio XAML design surface and select Edit Style or Edit Template (depending on the control you are right-clicking on).


2 Answers

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.

like image 87
Damascus Avatar answered Sep 21 '22 04:09

Damascus


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

like image 25
Allen Avatar answered Sep 18 '22 04:09

Allen