设置在代码中的WPF标签的样式属性? [英] Setting the Style property of a WPF Label in code?

查看:661
本文介绍了设置在代码中的WPF标签的样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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" />



不过,我想通过代码来初始化样式属性。我曾尝试:

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

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

label1.Style = "{StaticResource LabelTemplate}";



解决方案都不是有效的。

Neither solution was valid.

任何帮助,将不胜感激。)

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;



底部注:没有命名风格以关键字模板,你会最终结束了混乱的一个风格模板,而你不应该因为这是两个不同的概念。

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标签的样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆