【问题标题】:How to change style of the last row in a listview in Xamarin forms如何在 Xamarin 表单中更改列表视图中最后一行的样式
【发布时间】:2017-08-09 08:15:48
【问题描述】:

对于在 ListView 中显示的捐赠列表,我如何定位最后一行来编辑其样式?

【问题讨论】:

  • 您可以使用 DataTemplateSelector 来满足您的要求。但是您需要再添加一个属性来识别模型(ListView 项绑定模型)中的最后一行,例如布尔 IsLast。 developer.xamarin.com/guides/xamarin-forms/…
  • 尝试在列表视图中使用页脚
  • @MikeDarwish 你还有什么问题吗?
  • @PavanVParekh 我正在从服务器获取来自 Json 的数据,我无法将 IsLast 添加到对象中
  • @MikeDarwish 我不能使用页脚,因为我在列表中使用 ContextAction,所以页脚将无法访问 ContextAction

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


【解决方案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;
    }
    

结果:

编辑:

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

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

【讨论】:

  • 其实我是从 Json 数据中获取列表,所以无法将 IsLastRow 添加到对象中
  • 太棒了,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
相关资源
最近更新 更多