我想你可以去this post看看
这些是一些提示
首先禁用默认分隔符,这是通过向 ListView XAML 添加以下属性来完成的
SeparatorColor="Transparent"
在此之后,将完整的 ViewCell 内容包装在双 StackLayout 中!我知道这听起来有点矫枉过正,但这样你就不会遇到任何关于 ViewCell 内边距的 BoxView 问题……或其他东西。
第一个 StackLayout 的 BackgroundColor 应该设置为您希望分隔符的颜色,第二个 StackLayout 应该具有与其所在容器的其余部分相同的 BackgroundColor……在我们的示例中,页面设置为白色。请务必在第二个 StackLayout 的底部添加一个 Margin,因为这将代表我们分隔符的厚度!
我认为您可以使用此“边距”...当您的数据为空时,请删除边距,这样您就不应该有分隔符
<ListView x:Name="SeparatorListView"
SeparatorColor="Transparent"
ItemsSource="{Binding Persons}"
Margin="0,20,0,0"
RowHeight="60"
HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
BackgroundColor="White"
Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell IsEnabled="false">
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
BackgroundColor="Black">
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
BackgroundColor="White"
Margin="0,0,0,0.4">
<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand" Spacing="0">
<Label Text="{Binding FullName}" TextColor="Maroon" VerticalOptions="CenterAndExpand" Margin="20,0,20,0" />
<Label Text="{Binding Profession}" TextColor="Maroon" VerticalOptions="CenterAndExpand" Margin="20,0,20,0" />
</StackLayout>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
设置好之后,您将获得与这篇博文右上角的预览图相同的视觉效果。
作为奖励,如果您的页面的背景颜色不是白色,您可以省略其中一个 StackLayouts。因为如果是这种情况,您可以通过在 ListView 中使用透明度来使用该颜色作为分隔符颜色。
此示例,仅当页面本身的 BackgroundColor 也设置为 Olive 时才有效!
<ListView x:Name="SeparatorListView"
SeparatorColor="Transparent"
ItemsSource="{Binding Persons}"
Margin="0,20,0,0"
RowHeight="60"
HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
BackgroundColor="Olive"
Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell IsEnabled="false">
<StackLayout BackgroundColor="#f4eac3"
Padding="0,5,0,5"
HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<StackLayout BackgroundColor="Transparent"
HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand"
Spacing="0"
Margin="20,0,20,0">
<Label Text="{Binding FullName}" TextColor="Maroon" VerticalOptions="CenterAndExpand" />
<Label Text="{Binding Profession}" TextColor="Maroon" VerticalOptions="CenterAndExpand" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>