WPF实现主题更换的简单DEMO

实现主题更换功能主要是三个知识点:

  1. 动态资源 ( DynamicResource )
  2. INotifyPropertyChanged 接口
  3. 界面元素与数据模型的绑定 (MVVM中的ViewModel)

Demo 代码地址:GITHUB

下面开门见山,直奔主题

一、准备主题资源

在项目 (怎么建项目就不说了,百度上多得是) 下面新建一个文件夹 Themes,主题资源都放在这里面,这里我就简单实现了两个主题 Light /Dark,主题只包含背景颜色一个属性。

1. Themes

  1. 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>
  1. 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里面,这样方便管理和搜索。

  1. 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>,被 ComboBoxItemsSource 绑定,当集合内的元素发生变化时,ComboBoxItems 也会一起变化。

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 类用于绑定到 ComboBoxDataContext 属性,构造器中会初始化 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 控件来控制背景颜色,BorderBackground.Color 指向到动态资源 WindowBackgroundColor ,这个 WindowBackgroundColor 就是我们在主题资源中定义好的 Color 的 Key,因为需要动态更换主题,所以需要用DynamicResource 实现。

Border 背景动画比较简单,就是更改 SolidColorBrushColor 属性。

ComboBox 控件绑定了三个属性 :

  1. ItemsSource="{Binding Themes }" -> SettingsViewModel.Themes
  2. SelectedItem="{Binding SelectedTheme , Mode=TwoWay}" -> SettingsViewModel.SelectedTheme
  3. 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;
        }
    }
}

四、总结

关键点:

  1. 绑定 ComboBox(View层)ItemsSourceSelectedItem 两个属性到 SettingsViewModel (ViewModel层)
  2. ComboBoxSelectedItem 被更改后,会触发 ThemeManager 替换当前正在使用的主题资源(ThemeSource属性)
  3. 视图模型需要实现 INotifyPropertyChanged 接口来通知 WPF 框架属性被更改
  4. 使用 DynamicResource 引用 会改变的 资源,实现主题更换。

另外写的比较啰嗦,主要是给自己回过头来复习看的。。。这年头WPF也没什么市场了,估计也没什么人看吧 o(╥﹏╥)o

WPF实现主题更换的简单DEMO的更多相关文章

  1. WPF Modern UI 主题更换原理

    WPF Modern UI 主题更换原理 一 . 如何更换主题? 二 . 代码分析 代码路径 : FirstFloor.ModernUI.App / Content / SettingsAppeara ...

  2. Spring的简单demo

    ---------------------------------------- 开发一个Spring的简单Demo,具体的步骤如下: 1.构造一个maven项目 2.在maven项目的pom.xml ...

  3. activemq的搭建、启动,简单demo

    一.搭建activeMQ 在官网下载window版本,直接解压就可以. 二.启动 在解压完的目录/bin/win64,双击击activemq.bat,运行完之后打开浏览器,输入http://127.0 ...

  4. 设计模式之单例模式的简单demo

    /* * 设计模式之单例模式的简单demo */ class Single { /* * 创建一个本类对象. * 和get/set方法思想一样,类不能直接调用对象 * 所以用private限制权限 * ...

  5. 使用Spring缓存的简单Demo

    使用Spring缓存的简单Demo 1. 首先创建Maven工程,在Pom中配置 <dependency> <groupId>org.springframework</g ...

  6. Managed DirectX中的DirectShow应用(简单Demo及源码)

    阅读目录 介绍 准备工作 环境搭建 简单Demo 显示效果 其他 Demo下载 介绍 DirectX是Microsoft开发的基于Windows平台的一组API,它是为高速的实时动画渲染.交互式音乐和 ...

  7. angular实现了一个简单demo,angular-weibo-favorites

    前面必须说一段 帮客户做了一个过渡期的项目,唯一的要求就是速度,我只是会点儿基础的php,于是就用tp帮客户做了这个项目.最近和客户架构沟通,后期想把项目重新做一下,就用现在最流行的技术,暂时想的使用 ...

  8. Solr配置与简单Demo[转]

    Solr配置与简单Demo 简介: solr是基于Lucene Java搜索库的企业级全文搜索引擎,目前是apache的一个项目.它的官方网址在http://lucene.apache.org/sol ...

  9. 二维码简单Demo

    二维码简单Demo 一.视图 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name=&qu ...

随机推荐

  1. 【高速接口-RapidIO】5、Xilinx RapidIO核例子工程源码分析

    提示:本文的所有图片如果不清晰,请在浏览器的新建标签中打开或保存到本地打开 一.软件平台与硬件平台 软件平台: 操作系统:Windows 8.1 64-bit 开发套件:Vivado2015.4.2 ...

  2. Go语言结构

    目录 结构体定义 创建结构体实例 普通方式创建结构体实例 new()创建结构体实例 结构体实例初始化 结构体类型实例和指向它的指针内存布局 结构体的方法 面向对象 组合(继承) 结构体使用注意事项 G ...

  3. 《http权威指南》读书笔记12

    概述 最近对http很感兴趣,于是开始看<http权威指南>.别人都说这本书有点老了,而且内容太多.我个人觉得这本书写的太好了,非常长知识,让你知道关于http的很多概念,不仅告诉你怎么做 ...

  4. Java回调机制总结

    调用和回调机制 在一个应用系统中, 无论使用何种语言开发, 必然存在模块之间的调用, 调用的方式分为几种: 1.同步调用 同步调用是最基本并且最简单的一种调用方式, 类A的方法a()调用类B的方法b( ...

  5. 从github上克隆hibernate项目

    开发的项目用到了hibernate进行对象的持久化,最近项目上不忙,打算通过官方文档和源码来进行深度学习.第一步将hibernate部署到本地就折腾了好久,打算记录一下. 关于github的注册说一句 ...

  6. VMware Workstation Pro网络配置(WiFi配置等)

    常用技巧 连续按两下ctrl+alt,实现鼠标脱离 VMware Workstation Pro网络配置有几种模式: 桥接模式: 网络上的独立主机 占用路由器新IP资源 通过VMware Networ ...

  7. 过了所有技术面,却倒在 HR 一个问题上。。

    面试问离职原因,这是我们广大程序员朋友面试时逃不开的问题,如果答得不好,可能就影响了你整个的面试结果. 最近在栈长的Java技术栈vip群里,我也看到大家在讨论这个问题,其中有个朋友的回复栈长很有感触 ...

  8. 写了2年python,知道 if __name__ == '__main__' 什么意思吗?

    相信刚接触Python的你一定有过如此经历,把所有的代码都写在 if __name__ == '__main__'下,因为有人告诉你,这样比较符合 Pythonista 的代码风格. 殊不知这段代码的 ...

  9. .NET Core 如何调用 WebService

    0.使用背景 因为现在的项目都是基于 .NET Core 的,但是某些需要调用第三方的 WebService 服务,故有了此文章.其基本思路是通过微软提供的 Svcutil 工具生成代理类,然后通过 ...

  10. springBoot(2)---快速创建项目,初解jackson

    快速创建项目,初解jackson 一.快速创建项目 springboot官网提供了工具类自动创建web应用:网址:http://start.spring.io/ 官网页面 1.快速创建一个 选择web ...