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

MAUI 7中如何读取Resources/Styles/Colors.xaml内的颜色资源?

在MAUI 7中读取Colors.xaml里的Color资源

关键说明

你之前用的Xamarin嵌入式资源读取方法不适用于MAUI——Colors.xaml在MAUI中是编译后的ResourceDictionary,而非传统嵌入式资源,所以GetManifestResourceNames找不到它。另外,你提供的Colors.xaml代码有拼写错误:结尾标签</ReourceDictironary>应改为</ResourceDictionary>,这个错误会导致资源字典无法正常加载,需先修正。


方法1:通过全局资源直接读取(最常用)

默认MAUI项目会在App.xaml中自动合并Colors.xaml,直接调用全局资源字典即可获取颜色:

// 获取Primary颜色
if (Application.Current.Resources.TryGetValue("Primary", out object primaryObj) && primaryObj is Color primaryColor)
{
    // 在这里使用primaryColor
}

// 获取Secondary颜色
if (Application.Current.Resources.TryGetValue("Secondary", out object secondaryObj) && secondaryObj is Color secondaryColor)
{
    // 在这里使用secondaryColor
}

方法2:手动加载资源字典(未全局合并时用)

如果Colors.xaml没在App.xaml中合并,可手动加载后读取:

var colorsDict = new ResourceDictionary();
colorsDict.Source = new Uri("Resources/Styles/Colors.xaml", UriKind.Relative);

// 读取颜色
if (colorsDict.TryGetValue("Primary", out object primaryObj) && primaryObj is Color primaryColor)
{
    // 使用primaryColor
}

方法3:XAML中直接引用(补充)

如果是在XAML控件里使用,直接用StaticResource绑定即可:

<Label Text="示例文本" TextColor="{StaticResource Primary}" />

必要检查项

  • 确认Colors.xaml的生成操作为MauiXaml(默认配置,若不是需在文件属性中修改)
  • 确保App.xaml已合并资源字典(默认项目自带):
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <!-- 其他资源字典 -->
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    

内容的提问来源于stack exchange,提问作者Mark Wardell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:02:45