WPF实现主题更换的简单DEMO
实现主题更换功能主要是三个知识点:
- 动态资源 ( DynamicResource )
- INotifyPropertyChanged 接口
- 界面元素与数据模型的绑定 (MVVM中的ViewModel)
Demo 代码地址:GITHUB
下面开门见山,直奔主题
一、准备主题资源
在项目 (怎么建项目就不说了,百度上多得是) 下面新建一个文件夹 Themes,主题资源都放在这里面,这里我就简单实现了两个主题 Light /Dark,主题只包含背景颜色一个属性。
1. Themes
- Theme.Dark.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ModernUI.Example.Theme.Themes">
<Color x:Key="WindowBackgroundColor">#333</Color>
</ResourceDictionary>
- Theme.Light.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ModernUI.Example.Theme.Themes">
<Color x:Key="WindowBackgroundColor">#ffffff</Color>
</ResourceDictionary>
然后在程序的App.xaml中添加一个默认的主题
不同意义的资源最好分开到单独的文件里面,最后Merge到App.xaml里面,这样方便管理和搜索。
- App.xaml
<Application x:Class="ModernUI.Example.Theme.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ModernUI.Example.Theme"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/Theme.Light.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
二、实现视图模型 (ViewModel)
界面上我模仿 ModernUI ,使用ComboBox 控件来更换主题,所以这边需要实现一个视图模型用来被 ComboBox 绑定。
新建一个文件夹 Prensentation ,存放所有的数据模型类文件
1. NotifyPropertyChanged 类
NotifyPropertyChanged