Alternate row color ListView xamarin forms

淺唱寂寞╮ 提交于 2020-03-06 09:01:32

问题


I have bind on my ListView, an ObersvableCollection.

And i want to alternate my row color of my ListView.

I found lot of code, but didn't work for me... If you can share an example/sample !

Like this :

But i don't know how i can do that ?

I work with Visual Studio 2015 / Xamarin forms.

My project must be work with Android and IOS.

Thank for your help!


回答1:


There's no built in way to do this with XF. The simplest approach would be to include an Index property in your Item model (you would have to set it manually as you add it to your List/Collection) that determines the color. You could then bind the RowColor property to your ItemTemplate.

public class MyItem {

  public int Index { get; set; }
  public string Name { get; set; }

  public Color RowColor { 
    get {
      if (Index % 2) == 0))
        return Color.Red;
      else
        return Color.Blue; 
    }
  }
}

You could also use a ValueConverter to determine the Color based on the Index row - this would free your model from having to determine it's own color, which would be a cleaner implementation.




回答2:


You can use a custom ListView for that. This works, if your Cell inherits from ViewCell.

public class AlternatingListView : ListView
{
    public AlternatingListView(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
    { 
    }

    protected override void SetupContent(Cell content, int index)
    {
        base.SetupContent(content, index);

        var viewCell = content as ViewCell;
        viewCell.View.BackgroundColor = index % 2 == 0 ? Color.Blue : Color.Red;
    }     
}


来源:https://stackoverflow.com/questions/36840783/alternate-row-color-listview-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!