【发布时间】: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