繁体   English   中英

通过代码向我的元素添加样式

[英]Adding style to my element via code

如何以编程方式从ResourceDictionary向元素添加样式?

应用程式

<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中?

MainWindow.xaml文件中设置样式,如下所示:

<Label Name ="Example" Content="Hello World" Style="{StaticResource LabelTituloEstiloPadrao}">

或者,如果您想在MainWindow.xaml.cs文件中执行此操作:

l.Style = (Style)(this.Resources["LabelTituloEstiloPadrao"]);
l.Style = (Style) App.Current.Resources["LabelTituloEstiloPadrao"];

请注意,如果找不到资源密钥,这将引发异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM