正如我在评论中提到的,这可能是我之前发布的答案的一个变化。有关附带的博客文章,请参阅:
https://blog.verslu.is/stackoverflow-answers/alternate-row-color-listview/
你唯一需要做的就是换掉模板,不要让它们有不同的背景色,而是有不同的边距。
因此,创建一个DataTemplateSelector,如下所示:
public class MarginDataTemplateSelector : DataTemplateSelector
{
public DataTemplate EvenTemplate { get; set; }
public DataTemplate OddTemplate { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
// TODO: Maybe some more error handling here
return ((List<string>)((ListView)container).ItemsSource).IndexOf(item as string) % 2 == 0 ? EvenTemplate : OddTemplate;
}
}
你的XAML是这样的:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:AlternateRowColorSample" x:Class="AlternateRowColorSample.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="evenTemplate">
<ViewCell>
<Grid Margin="20,0,0,0">
<Label Text="{Binding .}" HorizontalOptions="Center" VerticalOptions="Center" />
</Grid>
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="oddTemplate">
<ViewCell>
<Grid Margin="0">
<Label Text="{Binding .}" TextColor="White" HorizontalOptions="Center" VerticalOptions="Center" />
</Grid>
</ViewCell>
</DataTemplate>
<local:MarginDataTemplateSelector x:Key="marginDataTemplateSelector"
EvenTemplate="{StaticResource evenTemplate}"
OddTemplate="{StaticResource oddTemplate}" />
</ResourceDictionary>
</ContentPage.Resources>
<ListView ItemTemplate="{StaticResource marginColorDataTemplateSelector}" ItemsSource="{Binding Items}">
</ListView>
</ContentPage>