Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c# - 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 :).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...