Xamarin.Forms ListView中的交替项Backgroundcolor

时间:2018-07-19 12:14:55

标签: listview colors xamarin.forms alternate

我正在使用ViewModel,并将ListView的ItemSource属性绑定到ViewModel的属性。 在Internet上搜索,找到了替代项目backgroundColor的解决方案,但找不到。

2 个答案:

答案 0 :(得分:4)

这可以通过多种方式完成。我认为更好的方法之一是通过DataTemplateSelector。在此处阅读文档:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector

创建一个包含两个模板的DataTemplateSelector,然后根据项目的索引选择它们:

public class AlternateColorDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate EvenTemplate { get; set; }
    public DataTemplate UnevenTemplate { 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 : UnevenTemplate;
    }
}

现在,在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 BackgroundColor="White">
                        <Label Text="{Binding .}" HorizontalOptions="Center" VerticalOptions="Center" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
            <DataTemplate x:Key="unevenTemplate">
                <ViewCell>
                    <Grid BackgroundColor="LightGray">
                        <Label Text="{Binding .}" TextColor="White" HorizontalOptions="Center" VerticalOptions="Center" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
            <local:AlternateColorDataTemplateSelector x:Key="alternateColorDataTemplateSelector"
                EvenTemplate="{StaticResource evenTemplate}"
                UnevenTemplate="{StaticResource unevenTemplate}" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <ListView ItemTemplate="{StaticResource alternateColorDataTemplateSelector}" ItemsSource="{Binding Items}">

    </ListView>
</ContentPage>

运行时,您将看到灰色和白色的行,如下所示:

Alternate row color

可以在此处找到完整的工作示例:https://github.com/jfversluis/AlternateRowColorSample

答案 1 :(得分:0)

您可以使用以下代码:

int position = 1;
foreach (var i in yourItemList)
{
   youranotherProperty = "";
   ItemBackgroundColor = (position % 2 == 0)? "Green" : "Red" ;
   position++;
}
相关问题