You have to make sure that the styles are in the file App.xaml
:
<Application x:Class="ChangeStyleHelp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="MyStyle" TargetType="{x:Type Label}">
<Setter Property="Background" Value="Green" />
</Style>
</Application.Resources>
</Application>
Code behind:
private void ChangeStyle_Click(object sender, RoutedEventArgs e)
{
Style style = new Style
{
TargetType = typeof(Label)
};
style.Setters.Add(new Setter(Label.BackgroundProperty, Brushes.Aquamarine));
Application.Current.Resources["MyStyle"] = style;
}
If the Style
is in the resource of Window
(Window.Resources
), then you need to write this
, or the name of the Window
:
private void ChangeStyle_Click(object sender, RoutedEventArgs e)
{
Style style = new Style
{
TargetType = typeof(Label)
};
style.Setters.Add(new Setter(Label.BackgroundProperty, Brushes.Aquamarine));
this.Resources["MyStyle"] = style;
}
As well, you can change the Style
this way: take an existing style and use of the element. Example:
<Application x:Class="ChangeStyleHelp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="AnotherWayStyle" TargetType="{x:Type Label}">
<Setter Property="Background" Value="Lavender" />
<Setter Property="Foreground" Value="OrangeRed" />
</Style>
</Application.Resources>
</Application>
Code behind:
private void AnotherWay_Click(object sender, RoutedEventArgs e)
{
label1.Style = (Style)Application.Current.Resources["AnotherWayStyle"];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…