WPF and Silverlight 学习笔记(十九):WPF更换主题
如果要做到一个应用程序其基本的内容不变,但改变整个应用程序的外观可以这样做:
- 对于每一套外观定义一个ResourceDictionary
- 在应用程序中,动态加载此应用程序(或窗体)的Resource
例如,如下的应用程序,在选择不同的用户时,显示不同的Canvas背景及图片:
主题样式A:
主题样式B:
主题样式C:
主题样式A的ResourceDictionary的XAML文件内容:
1: <ResourceDictionary
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
4: <!-- Canvas样式 -->
5: <Style TargetType="Canvas">
6: <Setter Property="Background">
7: <Setter.Value>
8: <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
9: <GradientStop Color="#FFFCF6F6" Offset="0"/>
10: <GradientStop Color="#FF201999" Offset="1"/>
11: </LinearGradientBrush>
12: </Setter.Value>
13: </Setter>
14: </Style>
15: </ResourceDictionary>
样式B、样式C的XAML代码与其类似,在这里省略。
窗体应用程序的XAML及CS代码如下:
1: <Window x:Class="StyleAndTemplete.TheMeDemo"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="TheMe Demo" Height="223" Width="319" ResizeMode="NoResize" Loaded="Window_Loaded">
5: <Canvas>
6: <Image Width="150" Height="150"
7: Canvas.Left="129" Canvas.Top="20"
8: x:Name="userImage"/>
9: <TextBlock Width="78" Height="20"
10: Text="Name:" TextWrapping="Wrap"
11: Canvas.Left="12" Canvas.Top="11"/>
12: <ComboBox Width="97" Height="27"
13: IsSynchronizedWithCurrentItem="True"
14: Canvas.Left="12" Canvas.Top="37"
15: x:Name="userName" SelectionChanged="userName_SelectionChanged" />
16: </Canvas>
17: </Window>
1: using System;
2: using System.Windows;
3: using System.Windows.Controls;
4: using System.Windows.Media.Imaging;
5:
6: namespace StyleAndTemplete
7: {
8: /// <summary>
9: /// Interaction logic for TheMeDemo.xaml
10: /// </summary>
11: public partial class TheMeDemo : Window
12: {
13: public TheMeDemo()
14: {
15: InitializeComponent();
16: }
17:
18: private void Window_Loaded(object sender, RoutedEventArgs e)
19: {
20: userName.Items.Add("Patrick");
21: userName.Items.Add("Abbey");
22: userName.Items.Add("Tobey");
23:
24: userName.SelectedIndex = 0;
25: }
26:
27: private void userName_SelectionChanged(object sender, SelectionChangedEventArgs e)
28: {
29: string selectedTitle = userName.SelectedItem.ToString();
30: string imgName = string.Format("/TitleImage/tile_{0}.png", selectedTitle);
31:
32: BitmapImage img = new BitmapImage(
33: new Uri(imgName,UriKind.Relative));
34:
35: userImage.Source = img;
36:
37: string dicName = string.Format(
38: "{0}Resource.xaml", selectedTitle);
39:
40: this.Resources = (ResourceDictionary)(Application.LoadComponent(
41: new Uri(dicName,UriKind.Relative)));
42: }
43: }
44: }
在微软WPF的示例程序中有一个更加复杂的示例:http://windowsclient.net/downloads/folders/wpfsamples/entry5097.aspx
本文版权归作者所有,未经同意,请勿用作商业用途。