如何在 Xamarin 表单中更改列表视图中最后一行的样式

How to change style of the last row in a listview in Xamarin forms

要在 ListView 中显示给定列表,我如何定位最后一行来编辑其样式?

  • 使用页脚

    <ListView.Footer>
       <StackLayout Orientation="Horizontal">
          <Label Text="Footer" TextColor="Gray" BackgroundColor="Blue" />
       </StackLayout>
    </ListView.Footer>
    
  • 使用DataTemplateSelector

    示例 here,并更改该项目中的某些内容

    1.In Person ,添加一个bool 属性 可以作为最后一行处理,并更改其构造函数:

    public bool IsLastRow { get; set; }
    
    public Person (string name, DateTime dob, string location , bool isLastRow)
    {
        Name = name;
        DateOfBirth = dob;
        Location = location;
        IsLastRow = false;
        IsLastRow = isLastRow;
    }
    

    2.In HomePage ,为模型列表设置值。

     var people = new List<Person> {
            new Person ("Kath", new DateTime (1985, 11, 20), "France" ,false),
            new Person ("Steve", new DateTime (1975, 1, 15), "USA",false),
            new Person ("Lucas", new DateTime (1988, 2, 5), "Germany",false),
            new Person ("John", new DateTime (1976, 2, 20), "USA",false),
            new Person ("Tariq", new DateTime (1987, 1, 10), "UK",false),
            new Person ("Jane", new DateTime (1982, 8, 30), "USA",false),
            new Person ("Tom", new DateTime (1977, 3, 10), "UK",true)
        };
    

    3.In PersonDataTemplateSelector ,修改判断模板的方法

    protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
    {
        return ((Person)item).IsLastRow ? ValidTemplate : InvalidTemplate;
    }
    

结果:

编辑:

如果您从 json 数据中获取列表,那么您应该遍历该列表并在 Step2 中手动将 isLastRow 添加到对象。 像这样:

int index = 0;
foreach(Person person in list){
     person.isLastRow = (index == list.Count-1);
     index ++;
}