如何从ResourceDictionary中以编程方式向元素添加样式?
App.xaml
<Application x:Class="Learning.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Learning">
<Application.Resources>
<Style TargetType="Label" x:Key="LabelTituloEstiloPadrao">
<Setter Property="Background" Value="White" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Margin" Value="40,20,0,0" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
Label l = new Label();
// Add Style in my label l
StackHorarios.Children.Add(l);
}
如何通过源代码将 LabelTituloEstiloPadraostyle 添加到标签l中?
答案 0 :(得分:1)
在MainWindow.xaml
文件中设置样式,如下所示:
<Label Name ="Example" Content="Hello World" Style="{StaticResource LabelTituloEstiloPadrao}">
或者如果您想在MainWindow.xaml.cs
文件中这样做:
l.Style = (Style)(this.Resources["LabelTituloEstiloPadrao"]);
答案 1 :(得分:1)
l.Style = (Style) App.Current.Resources["LabelTituloEstiloPadrao"];
请注意,如果找不到资源密钥,则会抛出异常