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

Dan*_*iel 72 c# wpf user-interface label

在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>
Run Code Online (Sandbox Code Playgroud)

这是为了为我的标签提供通用模板.

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

<Label Content="Movies" Style="{StaticResource LabelTemplate}" Name="label1" />
Run Code Online (Sandbox Code Playgroud)

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

label1.Style = new Style("{StaticResource LabelTemplate}");
Run Code Online (Sandbox Code Playgroud)

label1.Style = "{StaticResource LabelTemplate}";
Run Code Online (Sandbox Code Playgroud)

两种解决方案都无效.

任何帮助,将不胜感激 :).

Dam*_*cus 163

在代码中你想要获得风格?代码背后?

你应该这样写:

如果你是代码隐藏的:

Style style = this.FindResource("LabelTemplate") as Style;
label1.Style = style;
Run Code Online (Sandbox Code Playgroud)

如果你在别的地方

Style style = Application.Current.FindResource("LabelTemplate") as Style;
label1.Style = style;
Run Code Online (Sandbox Code Playgroud)

底部注意:不要Style用关键字命名a Template,你最终会混淆a Style和a Template,你不应该因为这两个是不同的概念.