通过代码向元素添加样式

时间:2018-08-02 15:57:10

标签: c# wpf

如何从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中?

2 个答案:

答案 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"];

请注意,如果找不到资源密钥,则会抛出异常