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

时间:2017-08-09 08:15:48

标签: listview xamarin.forms portable-class-library

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

1 个答案:

答案 0 :(得分:1)

  • 使用页脚

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

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

    1.在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.在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.在PersonDataTemplateSelector中,修改决定模板的方法

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

结果:enter image description here

修改

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

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