WinUI 3是否支持通过MergedDictionaries实现动态主题切换?
问题答复
WinUI 3 完全支持Application.Current.Resources.MergedDictionaries,且可以采用和Xamarin Forms几乎一致的动态加载、卸载资源字典的方案实现全局样式、颜色的动态修改,适配主题切换、自定义皮肤等需求。
核心实现示例
1. 提前准备资源字典
在项目中新建多个不同的资源字典文件(例如LightTheme.xaml、DarkTheme.xaml、CustomColorTheme.xaml等),在文件内定义统一键名的样式、颜色画笔等资源:
<!-- 示例:DarkTheme.xaml 内容 --> <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <SolidColorBrush x:Key="PageBackgroundBrush" Color="#121212"/> <SolidColorBrush x:Key="PrimaryTextBrush" Color="#FFFFFF"/> <Style TargetType="Button" x:Key="PrimaryButtonStyle"> <Setter Property="Background" Value="#2196F3"/> </Style> </ResourceDictionary>
2. 动态切换资源字典的代码
// 第一步:移除不需要的旧资源字典,避免键冲突 var toRemoveDict = Application.Current.Resources.MergedDictionaries .OfType<ResourceDictionary>() .FirstOrDefault(d => d.Source != null && d.Source.ToString().Contains("LightTheme.xaml")); if (toRemoveDict != null) { Application.Current.Resources.MergedDictionaries.Remove(toRemoveDict); } // 第二步:加载新的资源字典 var newThemeDict = new ResourceDictionary { Source = new Uri("ms-appx:///Themes/DarkTheme.xaml", UriKind.Absolute) }; Application.Current.Resources.MergedDictionaries.Add(newThemeDict);
如果多个资源字典存在同名资源键,后加入合并字典集合的资源优先级更高,会覆盖之前的同键资源
注意事项
- 资源字典的Uri路径要和项目实际存储路径匹配,打包到程序内的本地资源统一使用
ms-appx:///前缀 - 要实现修改后即时生效,页面控件的相关属性必须通过
{StaticResource}或{ThemeResource}绑定资源键,不能硬编码属性值 - 卸载资源字典时可以通过Source属性、自定义附加属性等规则筛选目标字典,避免误删系统默认合并字典或其他业务模块的资源字典
内容的提问来源于stack exchange,提问作者chuckp
相关产品推荐
相关产品推荐

