WPF 皮肤
1、新建两个ResourceDictionary的xaml,BlueSkin.xaml和YellowSkin.xaml;
<!--<SnippetBlueSkinMARKUP1>-->
<!-- Blue Skin -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SkinnedApplication">
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Blue" />
</Style>
<Style TargetType="{x:Type local:ChildWindow}">
<Setter Property="Background" Value="Blue" />
</Style>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="Background" Value="Blue" />
</Style>
</ResourceDictionary>
<!--</SnippetBlueSkinMARKUP2>-->
<!--<SnippetYellowSkinMARKUP1>-->
<!-- Yellow Skin -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SkinnedApplication">
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Yellow" />
</Style>
<Style TargetType="{x:Type local:ChildWindow}">
<Setter Property="Background" Value="Yellow" />
</Style>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="Background" Value="Yellow" />
</Style>
</ResourceDictionary>
<!--</SnippetYellowSkinMARKUP2>-->
2、App.xaml添加 Startup="App_Startup";
<Application x:Class="SkinnedApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SkinnedApplication"
StartupUri="MainWindow.xaml"
Startup="App_Startup">
<Application.Resources>
</Application.Resources>
</Application>
3、App.xaml.cs添加 对应方法,加载两个皮肤;
private void App_Startup(object sender, StartupEventArgs e)
{
Properties["Blue"] = (ResourceDictionary)LoadComponent(new Uri("BlueSkin.xaml", UriKind.Relative));
Properties["Yellow"] = (ResourceDictionary)LoadComponent(new Uri("YellowSkin.xaml", UriKind.Relative));
// Note: you can also use the following syntax:
// Skins["Yellow"] = new YellowSkin()
// But only as long as you implement the ResourceDictionary using markup and code-behind,
// use the x:Class attribute in markup, and call InitializeComponent() from code-behind, eg:
//
// <!-- Markup -->
// <ResourceDictionary
// xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
// xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
// xmlns:local="clr-namespace:SDKSample"
// x:Class="SDKSample.YellowSkin">
// ...
// </ResourceDictionary>
//
// // Code-behind
// public partial class YellowSkin : ResourceDictionary
// {
// public YellowSkin() { InitializeComponent(); }
// }
}
4、 MainWindow.xaml.cs中添加如下初始化代码;
//set initial skin
Application.Current.Resources = (ResourceDictionary)Application.Current.Properties["Blue"];
5、如果用下拉框选择,在事件中添加如下代码;
//Change the skin
var selectedValue = (string)e.AddedItems[0];
Application.Current.Resources = (ResourceDictionary)Application.Current.Properties[selectedValue];
maojie