我一直在尝试为我玩的纸牌游戏制作一个简单的计分应用程序。我只是想了解基本结构。因此,我创建了一个带有集合视图的框架,其中包含一些模拟数据来表示 XAML 中列中的玩家。我希望这些列填满所有水平空间(如果有),然后如果有更多,它会自动滚动。但是,例如,当只有 2 列时,我无法让我的列展开以占据整个宽度。我正在使用 .net MAUI 和 .net 8。任何帮助将不胜感激!这是我的代码。我并没有真正对基础项目创建启动进行任何重大更改,主要致力于生成的主页。
<?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="BlitzScorer.MainPage">
<ScrollView Padding="10">
<Frame VerticalOptions="Start" CornerRadius="20" BackgroundColor="LightGreen" Padding="10" >
<Grid RowDefinitions="*" ColumnDefinitions="*">
<CollectionView Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Horizontal"
HorizontalItemSpacing="5" />
</CollectionView.ItemsLayout>
<CollectionView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Player 1</x:String>
<x:String>Player 2</x:String>
</x:Array>
</CollectionView.ItemsSource>
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding .}" BackgroundColor="Beige" HorizontalOptions="FillAndExpand" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</Frame>
</ScrollView>
</ContentPage>
我尝试在多个区域上使用 FillAndExpand 属性,但 CollectionView 无论如何都不想占用空间。
正如社区所指出的,您可以删除
Grid
和 ScrollView
,这将自动填充所有水平空间。另外,您可能需要使用 Border
而不是 Frame
,因为在这种情况下边框更加灵活。例如,您可以为每个角指定单独的角半径。
下面是XAML代码供您参考:
<Border VerticalOptions="Start" BackgroundColor="LightGreen" Padding="10" >
<Border.StrokeShape>
<RoundRectangle CornerRadius="20,20,20,20"/>
</Border.StrokeShape>
<CollectionView HorizontalOptions="FillAndExpand">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Horizontal" HorizontalItemSpacing="5" />
</CollectionView.ItemsLayout>
<CollectionView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Player 1</x:String>
<x:String>Player 2</x:String>
</x:Array>
</CollectionView.ItemsSource>
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding .}" BackgroundColor="Beige"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Border>