WPF动态换肤的实现方法

1、在项目根目录下创建一个存放皮肤资源的文件夹 “Themes”

2、往Themes文件夹中添加资源字典

内容如:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:ThemeTest.Themes">
    <LinearGradientBrush x:Key="TitleBackground" StartPoint="0,0" EndPoint="0,1">
        <GradientStop Offset="0" Color="#337BCC"></GradientStop>
        <GradientStop Offset="1" Color="#003F9B"></GradientStop>
    </LinearGradientBrush>
    <SolidColorBrush x:Key="TitleForeground" Color="#ffffff"></SolidColorBrush>
</ResourceDictionary>

如图,我添加了3个资源字典文件,分别定义了深蓝,浅蓝,橙色三种皮肤的一些画笔

3、修改app.xaml文件如下

<Application x:Class="ThemeTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:ThemeTest"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/Theme_DarkBlue.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

这里是加载了深蓝为默认皮肤

4、界面调用对应皮肤的方法

<Grid Background="{DynamicResource TitleBackground}">

如上,需要使用{DynamicResource TitleBackground}这样的方式来调用动态资源

5、动态更换皮肤的方法

ResourceDictionary mResourceSkin = new ResourceDictionary() { Source = new Uri("/Themes/Theme_" + themeName + ".xaml", UriKind.RelativeOrAbsolute) };
Application.Current.Resources.MergedDictionaries[0] = mResourceSkin;

最终效果如下:

源码下载 https://download.youkuaiyun.com/download/xwt0511/10808356

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值