使用MvvmCross的WPF项目如何在App.xaml中设置MaterialDesignInXamlToolkit资源
MvvmCross项目中配置MaterialDesignInXamlToolkit主题的解决方案
MvxApplication本质继承自WPF原生的Application类,完全支持原生全局资源配置,你可以选择以下任意一种方法实现主题配置:
方法1:直接在App.xaml中声明资源(最推荐)
直接将你原来的主题资源配置嵌套到views:MvxApplication节点内即可,修改后的完整App.xaml代码如下:
<views:MvxApplication xmlns:views="clr-namespace:MvvmCross.Platforms.Wpf.Views;assembly=MvvmCross.Platforms.Wpf" x:Class="Overseer.Client.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" xmlns:local="clr-namespace:Overseer.Client" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <materialDesign:BundledTheme BaseTheme="Light" PrimaryColor="DeepPurple" SecondaryColor="Lime" /> <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </views:MvxApplication>
该方法和普通WPF项目的配置逻辑完全一致,资源维护更直观。
方法2:代码动态注入资源(适用于需要动态切换主题的场景)
如果后续有动态切换主题的需求,可以在App.xaml.cs的构造函数中手动注入资源字典,示例代码如下:
using MaterialDesignThemes.Wpf; using MvvmCross.Platforms.Wpf.Views; using System; namespace Overseer.Client { public partial class App : MvxApplication { public App() { // 注入Material Design主题配置 var bundledTheme = new BundledTheme { BaseTheme = BaseTheme.Light, PrimaryColor = PrimaryColor.DeepPurple, SecondaryColor = SecondaryColor.Lime }; Resources.MergedDictionaries.Add(bundledTheme); // 注入默认控件样式资源 var defaultStyles = new ResourceDictionary { Source = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml") }; Resources.MergedDictionaries.Add(defaultStyles); } } }
注意事项
- 两种方法二选一即可,优先选择方法1
- 若配置后样式不生效,请检查NuGet包
MaterialDesignThemes和MaterialDesignColors是否安装正确,且版本适配你的项目框架版本
内容的提问来源于stack exchange,提问作者Achille Depla
相关产品推荐
相关产品推荐

