WPF实现主题更换的简单DEMO
实现主题更换功能主要是三个知识点:
动态资源 ( DynamicResource )
INotifyPropertyChanged 接口
界面元素与数据模型的绑定 (MVVM中的ViewModel)
Demo 代码地址:GITHUB
下面开门见山,直奔主题
一、准备主题资源
在项目 (怎么建项目就不说了,百度上多得是) 下面新建一个文件夹 Themes,主题资源都放在这里面,这里我就简单实现了两个主题 Light /Dark,主题只包含背景颜色一个属性。
1. Themes
Theme.Dark.xaml
#333
Theme.Light.xaml
#ffffff
然后在程序的App.xaml中添加一个默认的主题
不同意义的资源最好分开到单独的文件里面,最后Merge到App.xaml里面,这样方便管理和搜索。
App.xaml
二、实现视图模型 (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; }
///
/// name to display on ui
///
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;
///
/// resource uri
///
public Uri Source
{
get => _source;
set
{
_source = value;
OnPropertyChanged();
}
}
}
4. LinkCollection 类
LinkCollection 继承自 ObservableCollection
,被 ComboBox 的 ItemsSource 绑定,当集合内的元素发生变化时,ComboBox 的 Items 也会一起变化。
class LinkCollection : ObservableCollection
{
///
/// Initializes a new instance of the class.
///
public LinkCollection()
{
}
///
/// Initializes a new instance of the class that contains specified links.
///
///
The links that are copied to this collection.
public LinkCollection(IEnumerable
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
///
/// get current theme resource dictionary
///
///
private ResourceDictionary GetThemeResourceDictionary()
{
return (from dictionary in Application.Current.Resources.MergedDictionaries
where dictionary.Contains("WindowBackgroundColor")
select dictionary).FirstOrDefault();
}
///
/// get source uri of current theme resource
///
///
resource uri
private Uri GetThemeSource()
{
var theme = GetThemeResourceDictionary();
if (theme == null)
return null;
return theme.Source;
}
///
/// set the current theme source
///
///
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);
}
}
///
/// current theme source
///
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
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,WPF Modern UI
标签: WPF, WPF ModernUI
好文要顶 关注我 收藏该文
ArthurRen
关注 - 1
粉丝 - 1
+加关注
1 0
« 上一篇:WPF Modern UI 主题更换原理
posted @ 2018-08-26 15:59 ArthurRen 阅读(275) 评论(1) 编辑 收藏
评论列表
#1楼 2018-08-27 12:10 收破烂
已读,支持楼主的贡献
支持(0)反对(0)
刷新评论刷新页面返回顶部
注册用户登录后才能发表评论,请 登录 或 注册,访问网站首页。
【推荐】超50万VC++源码: 大型组态工控、电力仿真CAD与GIS源码库!
【推荐】企业SaaS应用开发实战,快速构建企业运营/运维系统
【推荐】ActiveReports 报表控件,全面满足 .NET开发需求
qcloud0814
最新IT新闻:
· 聚光灯外的朱啸虎和金沙江创投:快速决策重在运营
· 四张图看清中国五大科技巨头最新财报 谁最牛?
· 币圈热衷境外建群:群内人数过万 现今逐渐成“死群”
· 滴滴系在厦门成立2家公司 分别从事股权投资和投资基金管理
· 要推拍照旗舰了?诺基亚手机新收获:PureView商标回归
» 更多新闻...
华为CH0822
最新知识库文章:
· 如何招到一个靠谱的程序员
· 一个故事看懂“区块链”
· 被踢出去的用户
· 成为一个有目标的学习者
· 历史转折中的“杭派工程师”
» 更多知识库文章...
公告
昵称:ArthurRen
园龄:1年1个月
粉丝:1
关注:1
+加关注
< 2018年8月 >
日 一 二 三 四 五 六
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8
搜索
常用链接
我的随笔
我的评论
我的参与
最新评论
我的标签
我的标签
Java(2)
Java 转行 自学(2)
WPF(2)
WPF ModernUI(2)
随笔分类
Java 自学之路(1)
WPF(2)
WPF Modern UI(2)
随笔档案
2018年8月 (3)
最新评论
1. Re:WPF实现主题更换的简单DEMO
已读,支持楼主的贡献
--收破烂
阅读排行榜
1. WPF实现主题更换的简单DEMO(273)
2. WPF Modern UI 主题更换原理(38)
评论排行榜
1. WPF实现主题更换的简单DEMO(1)
推荐排行榜
1. WPF实现主题更换的简单DEMOhttps://www.cnblogs.com/ArthurRen/p/9537645.html