我有一个水平方向和一个垂直方向的 CollectionView,它们都放置在 ScrollView 中。垂直方向的视图仅与其中的第一个项目一样高,并且在滚动视图进一步向下滚动之前它首先滚动。
如何使垂直方向的collectionview的高度适合页面的剩余高度,并使scrollview向上/向下滚动而不是先滚动collectionview?
XAML 尝试 1:
<VerticalStackLayout>
<CollectionView>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Horizontal"/>
</CollectionView.ItemsLayout>
</CollectionView>
<CollectionView>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"/>
</CollectionView.ItemsLayout>
</CollectionView>
</VerticalStackLayout>
XAML 尝试 2:
<ScrollView>
<VerticalStackLayout>
<CollectionView>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Horizontal"/>
</CollectionView.ItemsLayout>
</CollectionView>
<CollectionView>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"/>
</CollectionView.ItemsLayout>
</CollectionView>
</VerticalStackLayout>
</ScrollView>
这就是我的视图滚动的方式:
这就是我希望视图滚动的方式:
不鼓励在 .NET MAUI 中嵌套可滚动视图,这是正确的,因为这可能会导致潜在的无限布局循环,因为 ScrollView 是不受限制的,这将使调整同样不受限制的子级的大小变得困难。
最接近您想要的设计的方法是限制外部
ScrollView
仅垂直滚动,然后在内部添加一个包含两行的网格。在第一行中,您可以添加一个仅允许水平滚动的CollectionView
,同时必须具有固定的高度。在第二行中,其大小可能是无限的,然后您可以将 VerticalStackLayout
与 BindableLayout
结合起来,以便显示您想要垂直绑定到 的任何数据:XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="NestedScrollSample.MainPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:system="clr-namespace:System;assembly=System.Runtime"
x:Name="MyPage">
<ScrollView Orientation="Vertical">
<Grid RowDefinitions="120,*">
<CollectionView
Grid.Row="0"
HeightRequest="120"
ItemsSource="{Binding MyStrings, Source={x:Reference MyPage}}"
BackgroundColor="Orange">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Horizontal" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="system:String">
<Grid
WidthRequest="300"
HeightRequest="100"
VerticalOptions="Center">
<Label Text="{Binding}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<VerticalStackLayout
Grid.Row="1"
BackgroundColor="Aqua"
BindableLayout.ItemsSource="{Binding MyStrings, Source={x:Reference MyPage}}">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="system:String">
<Grid HeightRequest="300">
<Label Text="{Binding}" />
</Grid>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</Grid>
</ScrollView>
</ContentPage>
代码隐藏
using System.Collections.ObjectModel;
namespace NestedScrollSample;
public partial class MainPage : ContentPage
{
public ObservableCollection<string> MyStrings { get; }
public MainPage()
{
MyStrings = new()
{
"abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"
};
InitializeComponent();
}
}
免责声明:此代码仅用于演示目的,不遵循任何设计指南、建议或开发模式。