'Xamarin listview change color

How do change the color of the specific item in the listview? Ex( a listview of user that has status of active and inactive)

The active item background or border color will be set to green and inactive as red.



Solution 1:[1]

You should take a look at the 'VisualStateManager': https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/visual-state-manager

Solution 2:[2]

From my point of view, the easiest way is to change color of selected ViewCell using view cell tapped event as below:

  public partial class PageList : ContentPage
{
    ViewCell lastCell;
    public PageList()
    {
        InitializeComponent();

        listView.ItemsSource = new List<Contact>
        {
           new Contact { Name = "JP Morgan"},
           new Contact { Name ="Andrew Carnegie"},
           new Contact{ Name="Steve Jobs"}
        };
    }

    private void ViewCell_Tapped(object sender, EventArgs e)
    {
        if (lastCell != null)
            lastCell.View.BackgroundColor = Color.Red;
        var viewCell = (ViewCell)sender;
        if (viewCell.View != null)
        {
            viewCell.View.BackgroundColor = Color.Green;
            lastCell = viewCell;
        }
    }
}

Below is the listview in xaml,note that I set the background color of stacklayout to red as this is the default inactive color.

   <ListView x:Name="listView"
              SeparatorColor="Aqua">
            <ListView.ItemTemplate>
                <DataTemplate >
                    <ViewCell  Tapped="ViewCell_Tapped" >
                        <StackLayout  Background="red">
                            <Label Text="{Binding Name}"></Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
    </ListView>

enter image description here

Solution 3:[3]

Just figured out i can just add/make model that has string color in it

Like if you want you can just add public string color in your class model and then give a value everytime you call your list inside a foreach or if your old model has specific uses, you can make a new list model that has string color in it just for display purpose only and pass the old class model to your new display class model

And you can assign color in passing the old list to your display list

Idk if it is for better or for worst though but it works perfectly fine for me so... Yeah

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OneBigQuestion
Solution 2 Alexandar May - MSFT
Solution 3 Carljohn Lopez