您必须确保样式在文件中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>
后面的代码:
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;
}
如果Style
是在Window
( Window.Resources
) 的资源中,那么你需要写this
,或者 的名称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;
}
同样,您可以通过Style
这种方式进行更改:采用现有样式并使用元素。例子:
<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>
后面的代码:
private void AnotherWay_Click(object sender, RoutedEventArgs e)
{
label1.Style = (Style)Application.Current.Resources["AnotherWayStyle"];
}