如何为.NET MAUI中CollectionView的Grid练习项添加边框?
问题描述

这是我的练习列表,我希望在各个练习项之间添加边框,以免用户混淆每个练习对应的器材。以下是我的代码:
<StackLayout> <CollectionView ItemsSource="{Binding AllExerciseTypes}" SelectionMode="Single" BackgroundColor="{StaticResource TheBackgroundColor}" > <CollectionView.ItemTemplate> <DataTemplate x:DataType="Models:ExerciseType"> <Grid Padding="10" ColumnDefinitions="Auto,*" RowDefinitions="Auto, *"> <Label FontSize="Body" Grid.Column="1" FontAttributes="Bold" Text="{Binding Name}" /> <Label Grid.Row="1" Grid.Column="1" FontAttributes="Italic" Text="{Binding TargetedMuscle}" /> <Label Text= "{Binding Equipment}" FontAttributes="Italic" HorizontalTextAlignment="End" Grid.Column="2" Grid.Row="1"/> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </StackLayout> </ContentPage>
我曾尝试用Frame包裹Grid,但不清楚具体操作方法。
解决方案
直接把Grid嵌套在Frame内部,通过Frame的属性控制边框样式,同时调整布局间距即可。修改后的代码如下:
<StackLayout> <CollectionView ItemsSource="{Binding AllExerciseTypes}" SelectionMode="Single" BackgroundColor="{StaticResource TheBackgroundColor}" > <CollectionView.ItemTemplate> <DataTemplate x:DataType="Models:ExerciseType"> <!-- 用Frame包裹Grid,配置边框相关属性 --> <Frame BorderColor="#CCCCCC" <!-- 自定义边框颜色 --> CornerRadius="4" <!-- 边框圆角大小,不需要可设为0 --> Margin="5" <!-- 控制项与项之间的间距 --> Padding="0" <!-- 取消Frame默认内边距,保留Grid的Padding控制内部间距 --> BackgroundColor="{StaticResource TheBackgroundColor}"> <Grid Padding="10" ColumnDefinitions="Auto,*" RowDefinitions="Auto, *"> <Label FontSize="Body" Grid.Column="1" FontAttributes="Bold" Text="{Binding Name}" /> <Label Grid.Row="1" Grid.Column="1" FontAttributes="Italic" Text="{Binding TargetedMuscle}" /> <Label Text= "{Binding Equipment}" FontAttributes="Italic" HorizontalTextAlignment="End" Grid.Column="2" Grid.Row="1"/> </Grid> </Frame> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </StackLayout> </ContentPage>
关键调整说明:
BorderColor:设置边框颜色,可替换为项目主题色Margin:避免相邻项的边框紧贴,保证视觉区分度- 若不需要阴影,可添加
HasShadow="False"属性关闭Frame的默认阴影效果
内容的提问来源于stack exchange,提问作者dancho
相关产品推荐
相关产品推荐

