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. express使用记录

    express使用记录 文章用啥写?→→ VsCode. 代码用啥写?→→ VsCode. 编辑器下载:VsCode 一.windows下安装node.js环境: 下载地址 相比以前搭过的服务端语言的 ...

  2. Android开发 - 掌握ConstraintLayout(十)按比例设置视图大小

    有时候在布局界面的时候,UI要求某个View或者某张图片按比例显示,以适应不同的屏幕分辨率. 通常我们时通过自定义View或者引入第三方的库来解决.现在我们既然已经使用了ConstraintLayou ...

  3. W3bsafe]SQLmap过狗命令的利用+教程

    W3bsafe]SQLmap过狗命令的利用+教程 本文转自:i春秋社区 我就是那个爱装逼的小人   本屌又来装逼了 SQLmap注入的时候 有的肯定会被安全狗拦截吧 本屌来教各位过狗!过waf等安全狗 ...

  4. rabbitMQ的安装和创建用户

    rabbitMQ的安装和创建用户 在计算机科学中,消息队列(英语:Message queue)是 一种 进程间通信或同一进程的不同 线程 间的通信方式,软件的贮列用来处理一系列的输入,通常是来自用户. ...

  5. Warning: imagettfbbox(): Could not read font in XXX on line X

    今天在做图形验证码的时候,在windows运行好好的代码在CentOS下却无法运行了.报了如下警告 Warning: imagettfbbox(): Could not read font in /m ...

  6. WPF中TreeView控件的使用案例

    WPF总体来说还是比较方便的,其中变化最大的主要是Listview和Treeview控件,而且TreeView似乎在WPF是一个备受指责的控件,很多人说他不好用.我这个demo主要是在wpf中使用Tr ...

  7. Mybatis框架四:输入参数、输出参数

    输入参数可以有三种:简单类型,POJO,包装类 关于前两种: http://www.cnblogs.com/xuyiqing/p/8600888.html 这里写一下传递包装类参数: 一个POJO:U ...

  8. springbean的生命周期

    1.Spring对Bean进行实例化(相当于程序中的new Xx())2.Spring将值和Bean的引用注入进Bean对应的属性中3.如果Bean实现了BeanNameAware接口,Spring将 ...

  9. JavaScript的屏幕输出及时间函数

    Js屏幕输出 重定向页面输出: 更改输出流,如果在加载时使用则会正常排序,如果在HTML加载完成后使用,如点击事件,则会全部覆盖原HTML的内容. 1 <script> 2 //参数为输出 ...

  10. Redis 如何分析慢查询操作?

    什么是慢查询 和mysql的慢SQL日志分析一样,redis也有类似的功能,来帮助定位一些慢查询操作. Redis slowlog是Redis用来记录查询执行时间的日志系统. 查询执行时间指的是不包括 ...