Search code examples
maui

Background Image not showing in MAUI


I'm not seeing my background image and text displayed in a .NET MAUI app. Here is it code I used in an UWP app that worked that I am trying to convert to a .NET MAUI app.

<StackPanel Grid.Column="1" Margin="0,148,0,71" Grid.Row="2" Tapped="StackPanel_Tapped" Grid.RowSpan="2">
    <StackPanel.Background>
        <ImageBrush ImageSource="Assets/blueindex.jpg"/>
    </StackPanel.Background>
    <TextBlock x:Name="Answer1" TextWrapping="Wrap" Text="TextBlock" Margin="0,0,0,0" Foreground="Black" Height="210" TextAlignment="Center" FontSize="26.667" />
</StackPanel>

Here is the code I'm using, but no Text is displayed in my .NET MAUI app but the image is displayed.

<StackLayout Grid.Column="1" Grid.Row="5" Grid.RowSpan="2">
    <StackLayout.GestureRecognizers>
        <TapGestureRecognizer Tapped="StackLayout_Tapped" />
    </StackLayout.GestureRecognizers>
    <Image Source="blueindex.jpg" />
    <Label x:Name="Answer2" Text="TextBlock" TextColor="Black" FontSize="26.667" VerticalTextAlignment="Center" HeightRequest="210" />
</StackLayout>

What are some recommended changes to my .NET MAUI code?


Solution

  • StackLayout doesn't support background images directly (AFAIK), but you could wrap the StackLayout with a Grid and stack the image and the StackLayout in z-direction.

    The way you have it set up at the moment places the image vertically on top of the label, probably pushing it out of the viewport.

    So what you could do is something like this:

    <Grid>
    
        <Image
            Source="blueindex.jpg"
            Aspect="AspectFill"
            VerticalOptions="Fill"
            HorizontalOptions="Fill" />
    
        <VerticalStackLayout
            VerticalOptions="Fill"
            HorizontalOptions="Fill">
            <VerticalStackLayout.GestureRecognizers>
                <TapGestureRecognizer Tapped="StackLayout_Tapped" />
            </VerticalStackLayout.GestureRecognizers>
    
            <Label Text="TextBlock 1" />
            <Label Text="TextBlock 2" />
    
        </VerticalStackLayout>
    
    </Grid>
    

    This essentially places the image behind the StackLayout in z-direction.

    You may have to play around with the Aspect as well as the HorizontalOptions and VerticalOptions to make it fit your needs.