在代码中设置 WPF 标签的 Style 属性?

在 App.xaml 中,我有以下代码:

<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>

这意味着为我的标签提供一个通用模板。

在主 XAML 代码中,我有以下一行代码:

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

但是,我想通过代码初始化 Style 属性:

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

还有

label1.Style = "{StaticResource LabelTemplate}";

这两种解决方案都不成立。

如能提供任何帮助,我将不胜感激:)。

107270 次浏览

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.

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

Maybe an old question, but if you are trying W10 UWP app must use resources collection of each object or resources collection of Application object

KeyValuePair<object,object> styl = this.Resources
.FirstOrDefault(x => x.Key == "MyStyleTemplateName");
if (styl.Value != null)
Style MyStyle = (Style)styl.Value;

Where MyStyleTemplateName must be defined as a resource of this