您必须确保样式位于文件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;
}
此外,您可以通过以下方式更改样式
:使用现有样式并应用于元素。例如:
<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"]
}
Application.Current.Resources["Style1"] = style;
会替换你在 XAML 中写的Style
吗? - Nitesh