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

.NET MAUI应用中如何设置页面线性渐变背景?

.NET MAUI ContentPage 设置线性渐变背景的正确方法

问题核心:ContentPage.BackgroundColor仅接受Color类型值,而你定义的LinearGradientBrush属于Brush类型,直接赋值会失效;内联写法不生效也是因为错误使用了BackgroundColor属性。

以下是两种可行的解决方案:

方案1:通过StaticResource引用预定义的渐变笔刷

你的Colors.xaml中渐变笔刷的定义是正确的,只需要修改页面引用的属性为Background即可:

Colors.xaml 定义(无需修改)

<LinearGradientBrush x:Key="PageGradientBackground" EndPoint="1,1">
     <GradientStop
         Color="{StaticResource UIOffWhite}"
         Offset="0.1"/>
     <GradientStop
         Color="{StaticResource UILightGray}"
         Offset="0.6"/>
     <GradientStop
         Color="{StaticResource UIMidGray}"
         Offset="1.0"/>
</LinearGradientBrush>

页面引用修改

将BackgroundColor替换为Background:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Background="{StaticResource PageGradientBackground}">
    <!-- 页面内容 -->
</ContentPage>

方案2:内联定义渐变背景

同样需要使用Background属性而非BackgroundColor,正确的内联写法如下:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentPage.Background>
        <LinearGradientBrush EndPoint="1,1">
            <GradientStop Color="{StaticResource UIOffWhite}" Offset="0.1"/>
            <GradientStop Color="{StaticResource UILightGray}" Offset="0.6"/>
            <GradientStop Color="{StaticResource UIMidGray}" Offset="1.0"/>
        </LinearGradientBrush>
    </ContentPage.Background>
    <!-- 页面内容 -->
</ContentPage>

额外注意事项

确保Colors.xaml已被正确合并到App.xaml的资源字典中,否则StaticResource无法找到对应笔刷:

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:35:24