【问题标题】:Setting the Style property of a WPF Label in code?在代码中设置 WPF 标签的 Style 属性?
【发布时间】:2021-12-23 19:52:45
【问题描述】:

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

这两种解决方案均无效。

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

【问题讨论】:

  • 是否有任何理由从 UserControl 的代码隐藏中执行此操作?也许还有更优雅的解决方案。

标签: c# wpf user-interface label


【解决方案1】:

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

你应该这样写:

如果您在代码隐藏中:

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

如果你在其他地方

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

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

【讨论】:

【解决方案2】:

请检查 null 样式结果,否则你会很难过... ... 如果(风格!= null) this.Style = 风格;

【讨论】:

  • 当它为null时,您可以哭泣或人工纠正问题。
【解决方案3】:

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

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

其中 MyStyleTemplateName 必须定义为 this

的资源

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多