xmal:
<Window x:Class="wpfSkin.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:wpfSkin"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Margin="0,0,2,0">
<TextBox HorizontalAlignment="Left" Height="23" Margin="88,41,0,0" Text="TextBox" VerticalAlignment="Top" Width="120" />
<Button Content="Button" HorizontalAlignment="Left" Margin="242,42,0,0" VerticalAlignment="Top" Width="75"/>
<RadioButton Content="Blue Skin" Margin="112,135,307,160" Checked="RadioButton_Checked_1" />
<RadioButton Content="Red Skin" Margin="242,135,160,160" Checked="RadioButton_Checked" />
</Grid>
</Window>
添加文件夹skin,再添加resource Dictionary, xaml如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Style TargetType="TextBox">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="BorderThickness" Value="2" />
<Setter Property="BorderBrush" Value="DarkBlue" />
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="True">
<Setter Property="Background" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="Button">
<Setter Property="Background" Value="Cyan" />
</Style>
</ResourceDictionary>
后台代码cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Window wind = null;
Button btn = null;
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
wind = new Window() { Height = 300, Width = 300 };
btn = new Button() { Content = "anniu" };
wind.Content = btn;
wind.Show();
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
ChangeSkin("skin/red_rd.xaml");
}
void ChangeSkin(string skinRelativeUri)
{
var skinDictUri = new Uri(skinRelativeUri, UriKind.Relative);
var rd = Application.LoadComponent(skinDictUri) as ResourceDictionary;
wind.Resources.MergedDictionaries.Clear(); //只换单个window的皮肤
//btn.Resources.MergedDictionaries.Clear(); //只换button的皮肤
//Application.Current.Resources.MergedDictionaries.Clear(); //换整个应用程序的皮肤
btn.Resources.MergedDictionaries.Add(rd);
}
}