5

How do I set a page to have a linear background in a .NET MAUI app?

I tried defining a LinearGradientBrush in Colors.xaml and then assign it as a StaticResource -- see below -- but that doesn't seem to be working.

In Colors.xaml, I have this:

<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>

And then used it like this:

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

I also tried defining it inline but that didn't work either. This is not even allowed actually:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentPage.BackgroundColor>
        <LinearGradientBrush>
        </LinearGradientBrush>
    </ContentPage.BackgroundColor>
    <!-- ... -->
</ContentPage>

Any idea how I can have a gradient background for a ContentPage?

Julian
  • 5,290
  • 1
  • 17
  • 40
Sam
  • 26,817
  • 58
  • 206
  • 383
  • 3
    Does this may be answer your question: https://stackoverflow.com/questions/74034216/net-maui-background-vs-backgroundcolor-what-is-the-difference ? Maybe you can set `Background` instead of `BackgroundColor`? – Julian Nov 13 '22 at 19:08
  • @ewerspej Thanks, this solved a lot of XAML mysteries for me! – Al John Apr 18 '23 at 16:57

1 Answers1

5

You can use the LinearGradientBrush like the code below. You can put the LinearGradientBrush in the <ContentPage.Background> and it can work well.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp7.MainPage">
    <ContentPage.Background>
        
            <LinearGradientBrush EndPoint="1,0">
                <GradientStop Color="Yellow"
                          Offset="0.1" />
                <GradientStop Color="Green"
                          Offset="1.0" />
            </LinearGradientBrush>

    </ContentPage.Background>
</ContentPage>

For more information, you can refer to this article Linear gradient brushes.

Guangyu Bai - MSFT
  • 2,555
  • 1
  • 2
  • 8