WPF实现主题更换的简单DEMO
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 类实现 INotifyPropertyChanged 接口,是所有视图模型的基类,主要用于实现数据绑定功能。
abstract class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这里面用到了一个 [CallerMemberName] Attribute ,这个是.net 4.5里面的新特性,可以实现形参的自动填充,以后在属性中调用 OnPropertyChanged 方法就不用在输入形参了,这样更利于重构,不会因为更改属性名称后,忘记更改 OnPropertyChanged 的输入参数而导致出现BUG。具体可以参考 C# in depth (第五版) 16.2 节 的内容
2. Displayable 类
Displayable 用来实现界面呈现的数据,ComboBox Item上显示的字符串就是 DisplayName 这个属性
class Displayable : NotifyPropertyChanged
{
private string _displayName { get; set; }
/// <summary>
/// name to display on ui
/// </summary>
public string DisplayName
{
get => _displayName;
set
{
if (_displayName != value)
{
_displayName = value;
OnPropertyChanged();
}
}
}
}
3. Link 类
Link 类继承自 Displayable ,主要用于保存界面上显示的主题名称(DisplayName),以及主题资源的路径(Source)
class Link : Displayable
{
private Uri _source = null;
/// <summary>
/// resource uri
/// </summary>
public Uri Source
{
get => _source;
set
{
_source = value;
OnPropertyChanged();
}
}
}
4. LinkCollection 类
LinkCollection 继承自 ObservableCollection<Link>,被 ComboBox 的 ItemsSource 绑定,当集合内的元素发生变化时,ComboBox 的 Items 也会一起变化。
class LinkCollection : ObservableCollection<Link>
{
/// <summary>
/// Initializes a new instance of the <see cref="LinkCollection"/> class.
/// </summary>
public LinkCollection()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LinkCollection"/> class that contains specified links.
/// </summary>
/// <param name="links">The links that are copied to this collection.</param>
public LinkCollection(IEnumerable<Link> links)
{
if (links == null)
{
throw new ArgumentNullException("links");
}
foreach (var link in links)
{
Add(link);
}
}
}
5.ThemeManager 类
ThemeManager 类用于管理当前正在使用的主题资源,使用单例模式 (Singleton) 实现。
class ThemeManager : NotifyPropertyChanged
{
#region singletion
private static ThemeManager _current = null;
private static readonly object _lock = new object();
public static ThemeManager Current
{
get
{
if (_current == null)
{
lock (_lock)
{
if (_current == null)
{
_current = new ThemeManager();
}
}
}
return _current;
}
}
#endregion
/// <summary>
/// get current theme resource dictionary
/// </summary>
/// <returns></returns>
private ResourceDictionary GetThemeResourceDictionary()
{
return (from dictionary in Application.Current.Resources.MergedDictionaries
where dictionary.Contains("WindowBackgroundColor")
select dictionary).FirstOrDefault();
}
/// <summary>
/// get source uri of current theme resource
/// </summary>
/// <returns>resource uri</returns>
private Uri GetThemeSource()
{
var theme = GetThemeResourceDictionary();
if (theme == null)
return null;
return theme.Source;
}
/// <summary>
/// set the current theme source
/// </summary>
/// <param name="source"></param>
public void SetThemeSource(Uri source)
{
var oldTheme = GetThemeResourceDictionary();
var dictionaries = Application.Current.Resources.MergedDictionaries;
dictionaries.Add(new ResourceDictionary
{
Source = source
});
if (oldTheme != null)
{
dictionaries.Remove(oldTheme);
}
}
/// <summary>
/// current theme source
/// </summary>
public Uri ThemeSource
{
get => GetThemeSource();
set
{
if (value != null)
{
SetThemeSource(value);
OnPropertyChanged();
}
}
}
}
6. SettingsViewModel 类
SettingsViewModel 类用于绑定到 ComboBox 的 DataContext 属性,构造器中会初始化 Themes 属性,并将我们预先定义的主题资源添加进去。
ComboBox.SelectedItem -> SettingsViewModel.SelectedTheme
ComboBox.ItemsSource -> SettingsViewModel.Themes
class SettingsViewModel : NotifyPropertyChanged
{
public LinkCollection Themes { get; private set; }
private Link _selectedTheme = null;
public Link SelectedTheme
{
get => _selectedTheme;
set
{
if (value == null)
return;
if (_selectedTheme != value)
_selectedTheme = value;
ThemeManager.Current.ThemeSource = value.Source;
OnPropertyChanged();
}
}
public SettingsViewModel()
{
Themes = new LinkCollection()
{
new Link { DisplayName = "Light", Source = new Uri(@"Themes/Theme.Light.xaml" , UriKind.Relative) } ,
new Link { DisplayName = "Dark", Source = new Uri(@"Themes/Theme.Dark.xaml" , UriKind.Relative) }
};
SelectedTheme = Themes.FirstOrDefault(dcts => dcts.Source.Equals(ThemeManager.Current.ThemeSource));
}
}
三、实现视图(View)
1.MainWindwo.xaml
主窗口使用 Border 控件来控制背景颜色,Border 的 Background.Color 指向到动态资源 WindowBackgroundColor ,这个 WindowBackgroundColor 就是我们在主题资源中定义好的 Color 的 Key,因为需要动态更换主题,所以需要用DynamicResource 实现。
Border 背景动画比较简单,就是更改 SolidColorBrush 的 Color 属性。
ComboBox 控件绑定了三个属性 :
- ItemsSource="{Binding Themes }" -> SettingsViewModel.Themes
- SelectedItem="{Binding SelectedTheme , Mode=TwoWay}" -> SettingsViewModel.SelectedTheme
- DisplayMemberPath="DisplayName" -> SettingsViewModel.SelectedTheme.DisplayName
<Window ...>
<Grid>
<Border x:Name="Border">
<Border.Background>
<SolidColorBrush x:Name="WindowBackground" Color="{DynamicResource WindowBackgroundColor}"/>
</Border.Background>
<Border.Resources>
<Storyboard x:Key="BorderBackcolorAnimation">
<ColorAnimation
Storyboard.TargetName="WindowBackground" Storyboard.TargetProperty="Color"
To="{DynamicResource WindowBackgroundColor}"
Duration="0:0:0.5" AutoReverse="False">
</ColorAnimation>
</Storyboard>
</Border.Resources>
<ComboBox x:Name="ThemeComboBox"
VerticalAlignment="Top" HorizontalAlignment="Left" Margin="30,10,0,0" Width="150"
DisplayMemberPath="DisplayName"
ItemsSource="{Binding Themes }"
SelectedItem="{Binding SelectedTheme , Mode=TwoWay}" >
</ComboBox>
</Border>
</Grid>
</Window>
2. MainWindow.cs
后台代码将 ComboBox.DataContext 引用到 SettingsViewModel ,实现数据绑定,同时监听 ThemeManager.Current.PropertyChanged 事件,触发背景动画
public partial class MainWindow : Window
{
private Storyboard _backcolorStopyboard = null;
public MainWindow()
{
InitializeComponent();
ThemeComboBox.DataContext = new Presentation.SettingsViewModel();
Presentation.ThemeManager.Current.PropertyChanged += AppearanceManager_PropertyChanged;
}
private void AppearanceManager_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_backcolorStopyboard != null)
{
_backcolorStopyboard.Begin();
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (Border != null)
{
_backcolorStopyboard = Border.Resources["BorderBackcolorAnimation"] as Storyboard;
}
}
}
四、总结
关键点:
- 绑定 ComboBox(View层) 的 ItemsSource 和 SelectedItem 两个属性到 SettingsViewModel (ViewModel层)
- ComboBox 的 SelectedItem 被更改后,会触发 ThemeManager 替换当前正在使用的主题资源(ThemeSource属性)
- 视图模型需要实现 INotifyPropertyChanged 接口来通知 WPF 框架属性被更改
- 使用 DynamicResource 引用 会改变的 资源,实现主题更换。
另外写的比较啰嗦,主要是给自己回过头来复习看的。。。这年头WPF也没什么市场了,估计也没什么人看吧 o(╥﹏╥)o
WPF实现主题更换的简单DEMO的更多相关文章
- WPF Modern UI 主题更换原理
WPF Modern UI 主题更换原理 一 . 如何更换主题? 二 . 代码分析 代码路径 : FirstFloor.ModernUI.App / Content / SettingsAppeara ...
- Spring的简单demo
---------------------------------------- 开发一个Spring的简单Demo,具体的步骤如下: 1.构造一个maven项目 2.在maven项目的pom.xml ...
- activemq的搭建、启动,简单demo
一.搭建activeMQ 在官网下载window版本,直接解压就可以. 二.启动 在解压完的目录/bin/win64,双击击activemq.bat,运行完之后打开浏览器,输入http://127.0 ...
- 设计模式之单例模式的简单demo
/* * 设计模式之单例模式的简单demo */ class Single { /* * 创建一个本类对象. * 和get/set方法思想一样,类不能直接调用对象 * 所以用private限制权限 * ...
- 使用Spring缓存的简单Demo
使用Spring缓存的简单Demo 1. 首先创建Maven工程,在Pom中配置 <dependency> <groupId>org.springframework</g ...
- Managed DirectX中的DirectShow应用(简单Demo及源码)
阅读目录 介绍 准备工作 环境搭建 简单Demo 显示效果 其他 Demo下载 介绍 DirectX是Microsoft开发的基于Windows平台的一组API,它是为高速的实时动画渲染.交互式音乐和 ...
- angular实现了一个简单demo,angular-weibo-favorites
前面必须说一段 帮客户做了一个过渡期的项目,唯一的要求就是速度,我只是会点儿基础的php,于是就用tp帮客户做了这个项目.最近和客户架构沟通,后期想把项目重新做一下,就用现在最流行的技术,暂时想的使用 ...
- Solr配置与简单Demo[转]
Solr配置与简单Demo 简介: solr是基于Lucene Java搜索库的企业级全文搜索引擎,目前是apache的一个项目.它的官方网址在http://lucene.apache.org/sol ...
- 二维码简单Demo
二维码简单Demo 一.视图 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name=&qu ...
随机推荐
- Python面向对象5:类的常用魔术方法
魔术方法就是不需要人为调用的方法,基本是在特定的时刻自动触发- 魔术方法的统一的特征,方法名被前后各两个下滑线包裹 - 操作类 - `__init__`: 构造函数 - `__new__`: 对象实例 ...
- Docker学习笔记-Docker for Linux 安装
前言: 环境:centos7.5 64 位 正文: Docker 软件包已经包括在默认的 CentOS-Extras 软件源里.因此想要安装 docker,只需要运行下面的 yum 命令: yum i ...
- C语言中关键字restrict的概念,使用范围,例子
概念: restrict,C语言中的一种类型限定符(Type Qualifiers),用于告诉编译器,对象已经被指针所引用,不能通过除该指针外所有其他直接或间接的方式修改该对象的内容. 渊源: res ...
- HBase——HMaster启动之二(HMaster线程的调用)
紧接着上一节HMaster的构建完成.接下来会调用HMaster调用master.start(),master.join(). 由HMaster的继承关系,很明显,他是Runnable的子类.也就是说 ...
- ASP .NET CORE 根据环境变量支持多个 appsettings.json
0.背景 在开发项目的过程当中,生产环境与调试环境的配置肯定是不一样的.拿个最简单的例子来说,比如连接字符串这种东西,调试环境肯定是不能连接生产数据库的.在之前的话,这种情况只能说是你 COPY 两个 ...
- 11.Django2.0文档
第四章 模板 1.标签 (1)if/else {% if %} 标签检查(evaluate)一个变量,如果这个变量为真(即,变量存在,非空,不是布尔值假),系统会显示在 {% if %} 和 {% e ...
- springBoot(6)---过滤器,监听器,拦截器
过滤器,监听器,拦截器 一.理解它们 看里十几篇博客,总算有点小明白,总的来讲,两张图可以让我看明白点. 通过两幅图我们可以理解拦截器和过滤器的特点 1.过滤器 过滤器是在请求进入tomcat容器后, ...
- selenium python 一些操作和定位收集
(—)滚动条操作 python中selenium操作下拉滚动条方法汇总 selenium_webdriver(python)控制浏览器滚动条 selenium+Python(select定位) Sel ...
- Python快速学习02:基本数据类型 & 序列
前言 系列文章:[传送门] 也就每点一点点的开始咯,“还有两年时间,两年可以学很多东西的” Python ['paɪθən] n. 巨蛇,大蟒 基本数据类型 变量不需要声明 a=10 # int 整 ...
- java中String类为什么不可变?
在面试中经常遇到这样的问题:1.什么是不可变对象.不可变对象有什么好处.在什么情景下使用它,或者更具体一点,java的String类为什么要设置成不可变类型? 1.不可变对象,顾名思义就是创建后的对象 ...