You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中用C#创建ResourceDictionary的高效实现方案咨询

.NET MAUI中用C#创建合并ResourceDictionary的可行方案

我正在为.NET MAUI的初始化流程开发C#工具类,目的是避免设置流程分散在5个文件中。需要将以下XAML代码转换为C#实现:

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
        <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

我尝试过两种方法但都失败了:

  • 使用ResourceDictionary.RDSourceTypeConverter的ConvertFromString方法,抛出未实现异常
  • 直接为新创建的ResourceDictionary设置Source为相对Uri,报错提示必须使用XAML

对应的尝试代码:

var converter = new ResourceDictionary.RDSourceTypeConverter();

try
{
    var c = converter.ConvertFromString(resourcepath);
}
catch (Exception ex)
{
    // thrown not implemented exception
}

resourceDictionary.MergedDictionaries.Add(new()
{
    Source = new Uri(resourcepath, UriKind.Relative) // throws exception saying I need to use XAML
});

可行的无性能损耗方案

以下是两种可靠的实现方式,均不会影响性能:

方法1:使用LoadFromXaml扩展方法

需要引用Microsoft.Maui.Controls.Xaml命名空间,直接读取XAML文件内容并加载到ResourceDictionary中:

using Microsoft.Maui.Controls.Xaml;
using System.IO;

// 创建主资源字典
var mainResourceDict = new ResourceDictionary();

// 加载并添加Colors.xaml
var colorsDict = new ResourceDictionary();
colorsDict.LoadFromXaml(File.ReadAllText("Resources/Styles/Colors.xaml"));
mainResourceDict.MergedDictionaries.Add(colorsDict);

// 加载并添加Styles.xaml
var stylesDict = new ResourceDictionary();
stylesDict.LoadFromXaml(File.ReadAllText("Resources/Styles/Styles.xaml"));
mainResourceDict.MergedDictionaries.Add(stylesDict);

方法2:通过ResourceDictionary构造函数加载(推荐)

如果你的XAML文件被标记为Embedded Resource(在属性窗口设置“生成操作”为Embedded Resource),可以直接通过构造函数加载,这种方式性能更优,因为资源会被嵌入程序集:

// 注意替换为你的项目程序集名称
var assembly = typeof(App).Assembly;

var mainResourceDict = new ResourceDictionary();

// 加载Colors.xaml(嵌入资源路径格式:程序集名.文件夹结构.文件名.xaml)
var colorsDict = new ResourceDictionary(assembly, "YourProjectName.Resources.Styles.Colors.xaml");
mainResourceDict.MergedDictionaries.Add(colorsDict);

// 加载Styles.xaml
var stylesDict = new ResourceDictionary(assembly, "YourProjectName.Resources.Styles.Styles.xaml");
mainResourceDict.MergedDictionaries.Add(stylesDict);

注意事项

  • 如果使用方法2,确保XAML文件的“生成操作”设置为Embedded Resource,否则会找不到资源
  • 两种方法都可以将合并后的mainResourceDict赋值给Application.Current.Resources,完成全局资源初始化

内容的提问来源于stack exchange,提问作者Neville Nazerane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:31:17