85

在 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}";

两种解决方案均无效。

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

4

3 回答 3

196

您试图在代码中的哪个位置获取样式?后面的代码?

你应该这样写:

如果您在代码隐藏中:

Style style = this.FindResource("LabelTemplate") as Style;
label1.Style = style;

如果你在别的地方

Style style = Application.Current.FindResource("LabelTemplate") as Style;
label1.Style = style;

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

于 2012-05-21T14:18:18.477 回答
3

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

于 2014-05-09T10:23:25.643 回答
0

也许是一个老问题,但如果你正在尝试 W10 UWP 应用程序必须使用每个对象的资源集合或应用程序对象的资源集合

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

其中MyStyleTemplateName必须定义为this的资源

于 2016-03-22T13:08:01.587 回答