代码下载:http://download.csdn.net/detail/lh806732/8454189
1、效果
2、工程目录
2.1 如工程目录所示,在工程下创建Resources目录,并在Resources创建Themes目录用于存放主题资源。
2.2 在Themes目录下创建Default和Green资源文件,并修改相应的Style(代码略)。
2.3 在App.config中添加如下代码:
<appSettings>
<add key="Theme_Default" value="/Resources/Themes/Default.xaml" />
<add key="Theme_Green" value="/Resources/Themes/Green.xaml" />
</appSettings>
3、自定义一个Themes类用于设置当前的主题
public static class Themes
{
public static ResourceDictionary mResourceSkin = null;
public static void SetCurrentTheme(string name = "Default")
{
string themeKey = "Theme_";
themeKey += name;
string themeUri = ConfigurationManager.AppSettings.Get(themeKey);
if (string.IsNullOrEmpty(themeUri))
{
return;
}
if (App.Current.Resources.MergedDictionaries.Contains(mResourceSkin))
{
App.Current.Resources.MergedDictionaries.Remove(mResourceSkin);
}
mResourceSkin = new ResourceDictionary() { Source = new Uri(themeUri, UriKind.RelativeOrAbsolute) };
App.Current.Resources.MergedDictionaries.Add(mResourceSkin);
}
}
4、测试
4.1 主窗口布局
<Grid Style="{DynamicResource GridStyle}">
<!-- 动态绑定资源 -->
<StackPanel Style="{DynamicResource DialogStyle}">
<TextBlock Text="Loading..." Style="{DynamicResource HeadingStyle}" Margin="20"/>
<ProgressBar Value="35" MinHeight="20" Margin="20"/>
<Button Content="Cancel" Width="80" Height="30" FontSize="20" Style="{DynamicResource CancelButtonStyle}"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="设置主题皮肤" FontSize="20" VerticalAlignment="Center"/>
<ComboBox x:Name="combobox_ThemeChanger" Margin="5,0,0,0"
FontSize="20" MinWidth="100" MaxWidth="150" MinHeight="30"
SelectionChanged="combobox_ThemeChanger_SelectionChanged"
SelectedIndex="0"
>
<!--<ComboBoxItem Content="Default"/>
<ComboBoxItem Content="Green"/>-->
</ComboBox>
</StackPanel>
</StackPanel>
</Grid>
4.2 C#代码
public partial class MainWindow : Window
{
Dictionary<string, string> ThemeSource { get; set; }
public MainWindow()
{
InitializeComponent();
ThemeSource = new Dictionary<string, string>();
ThemeSource.Add("默认主题", "Default");
ThemeSource.Add("草绿主题", "Green");
combobox_ThemeChanger.ItemsSource = ThemeSource.Keys;
}
private void combobox_ThemeChanger_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cb = sender as ComboBox;
string themeKey="";
string theme ="";
themeKey = cb.SelectedItem.ToString();
theme = ThemeSource[themeKey];
Themes.SetCurrentTheme(theme);
}
}
本文介绍如何在WPF应用中实现动态修改皮肤。通过创建Themes目录存储不同主题资源,详细步骤包括设置资源文件、修改Style以及使用自定义Themes类来切换主题。附带代码下载链接。

1770

被折叠的 条评论
为什么被折叠?



