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

如何在XAML中引用颜色?——.NET MAUI项目技术咨询

在.NET MAUI中通过{Color}标记扩展引用Colors.xaml中的颜色

1. 确保Colors.xaml中的颜色定义规范

在Resources/Styles/Colors.xaml里,颜色需以Color类型的资源形式定义,示例代码如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- 自定义颜色示例 -->
    <Color x:Key="MyCustomColor">#FF2ECC71</Color>
</ResourceDictionary>

2. 全局加载资源字典

要让所有XAML文件都能访问到Colors.xaml里的资源,需在App.xaml中合并该资源字典,配置示例:

<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="你的项目命名空间.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- 引入Colors.xaml资源 -->
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <!-- 可继续合并其他资源字典(如Styles.xaml) -->
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

3. 在目标XAML中引用颜色

完成上述配置后,就能按你期望的方式直接引用颜色,示例:

<StackLayout
    BackgroundColor="{Color MyCustomColor}"
    Orientation="Horizontal"
    VerticalOptions="Start">
    <!-- 子元素内容 -->
</StackLayout>

常见问题排查

  • 检查MyCustomColor的x:Key拼写是否完全一致(区分大小写)
  • 确认App.xaml中Source属性里的Colors.xaml路径正确
  • 若引用失效,尝试清理项目并重新构建,避免缓存干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:12:06