Search code examples
c#.netxamllayoutmaui

Fixed image on top of scrollview in .NET MAUI / XAML


I'm using <ScrollView> to make the page scrollable and I'm trying to use <AbsoluteLayout> to have a fixed image to the top of the page. The image must maintain its fixed position even when scrolling down the page. Placing the <AbsoluteLayout> outside of the <ScrollView> is not allowed but inside of it, it will scroll with the page. Getting rid of the <ScrollView> entirely would disable scrolling as well.

How do I put an fixed full width image on top of the screen, while still maintaining a scrollable page?

<ScrollView>
    <Grid RowDefinitions="auto,auto,auto" ColumnDefinitions="*" x:DataType="local:Project">
        <CarouselView Grid.Row="0" 
                  ItemsSource="{Binding images}" 
                  IndicatorView="indicatorView"
                  IsSwipeEnabled="True">
            <CarouselView.ItemsLayout>
                <LinearItemsLayout SnapPointsType="MandatorySingle" 
                               SnapPointsAlignment="Center" 
                               Orientation="Horizontal"/>
            </CarouselView.ItemsLayout>
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding .}"
                       Aspect="AspectFill"/>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
        <IndicatorView Grid.Row="1" x:Name="indicatorView"/>
        <ScrollView Grid.Row="2" Grid.Column="0" Margin="8,0,8,32">
            <VerticalStackLayout>
                <!-- Page content here -->
            </VerticalStackLayout>
        </ScrollView>
        <AbsoluteLayout>
            <!-- What to do here??? -->
            <VerticalStackLayout AbsoluteLayout.LayoutFlags="PositionProportional"
                                 AbsoluteLayout.LayoutBounds="0,0,100,100">
                <Image Source="test.svg" Aspect="AspectFill"/>
            </VerticalStackLayout>
        </AbsoluteLayout>
    </Grid>
</ScrollView>

The same goes for any <AbsoluteLayout> element, like a floating action button, it just scrolls with the page.


Solution

  • One way is to put the ScrollView into the AbsoluteLayout. In AbsoluteLayout, you could set the image at fixed location. Consider the following code:

    ...
    <AbsoluteLayout>
       <ScrollView  WidthRequest="400"  HeightRequest="500">
           <VerticalStackLayout>
           ...
           </VerticalStackLayout>
       </ScrollView>
       <VerticalStackLayout AbsoluteLayout.LayoutFlags="PositionProportional"
                 AbsoluteLayout.LayoutBounds="0,0,100,100" >
                        <Image Source="test.svg" Aspect="AspectFill"/>
        </VerticalStackLayout>
    </AbsoluteLayout>
    

    Then when scrolling the page, the image will stay at a fixed place.

    Hope it works.