.Net MAUI 中的可滚动标题

问题描述 投票:0回答:1

我想设计一个当用户向上滚动并粘在顶部时尺寸减小的标题。我想要的设计是在标题中显示一个徽标,覆盖大约 50% 的屏幕。然而,滚动后,它会缩小到原始大小的 20% 左右,并变成标题文本。

我尝试过使用框架,但仍然无法实现这一点。

c# xaml maui
1个回答
0
投票

通过结合使用 ScrollView、用于定位的 AbsoluteLayout 和检测滚动的事件处理,可以在 .NET MAUI 中创建动态更改大小的可滚动标头。您需要监听滚动事件并相应地调整标题和徽标的大小。

以下是如何编写 XAML 和 C# 代码来实现此效果的示例:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="YourNamespace.YourPage"
         x:Name="thisPage">
<ScrollView x:Name="scrollView"
            Scrolled="OnScrollViewScrolled">
    <VerticalStackLayout>
        <!-- This is the header -->
        <AbsoluteLayout x:Name="header"
                        HeightRequest="200"  <!-- Initial height -->
                        BackgroundColor="LightGray">
            <Image Source="your_logo.png"
                   AbsoluteLayout.LayoutBounds="0.5, 0.5, 1, 1"
                   AbsoluteLayout.LayoutFlags="All"
                   Aspect="AspectFit"
                   x:Name="headerLogo"/>
            <Label Text="Your Title"
                   FontSize="Large"
                   AbsoluteLayout.LayoutBounds="0.5, 0.5, -1, -1"
                   AbsoluteLayout.LayoutFlags="PositionProportional"
                   IsVisible="False"
                   x:Name="headerTitle"/>
        </AbsoluteLayout>

        <!-- The rest of your page content goes here -->
        <!-- ... -->
    </VerticalStackLayout>
</ScrollView>
public partial class YourPage : ContentPage
{
    public YourPage()
    {
        InitializeComponent();
    }

    private void OnScrollViewScrolled(object sender, ScrolledEventArgs e)
    {
        const double startHeight = 200; // The initial height of the header
        const double endHeight = 40;    // The final height of the header when scrolled
        double scrollRatio = Math.Min(1, e.ScrollY / startHeight);

        // Calculate new height based on the scroll ratio
        double newHeight = startHeight - ((startHeight - endHeight) * scrollRatio);
        header.HeightRequest = newHeight;

        // Determine whether the logo or the title should be visible
        headerLogo.IsVisible = newHeight > endHeight;
        headerTitle.IsVisible = newHeight <= endHeight;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.