在代码中设置 WPF 标签的 Style 属性? [英] Setting the Style property of a WPF Label in code?
问题描述
在 App.xaml 中,我有以下代码:
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.
在主要的 XAML 代码中,我有以下代码行:
In the main XAML code, I have the following line of code:
<Label Content="Movies" Style="{StaticResource LabelTemplate}" Name="label1" />
但是,我想通过代码来初始化 Style 属性.我试过了:
However, I'd like to initialize the Style property through code. I have tried:
label1.Style = new Style("{StaticResource LabelTemplate}");
和
label1.Style = "{StaticResource LabelTemplate}";
两种解决方案都无效.
任何帮助将不胜感激:)
Any help would be appreciated :).
推荐答案
您试图在代码中的哪个位置获得样式?背后的代码?
Where in code are you trying to get the style? Code behind?
你应该这样写:
如果您使用代码隐藏:
Style style = this.FindResource("LabelTemplate") as Style;
label1.Style = style;
如果你在别的地方
Style style = Application.Current.FindResource("LabelTemplate") as Style;
label1.Style = style;
后记:不要用关键字Template
命名Style
,你最终会混淆Style
和 Template
,你不应该因为这是两个不同的概念.
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.
这篇关于在代码中设置 WPF 标签的 Style 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!