简体   繁体   中英

how to give different text color for each item of listview in xamarin forms

I have list of string which is getting assigned to the listview in xamarin forms as in below code

List<string> list = new List<string>();

list.Add("A");
list.Add("B");
list.Add("C");
list.Add("D");

var listview = new ListView(); 

listview.ItemsSource = list;

Content = listview;

How to show all the listview items text in different color? I want to show it like these:

A --> in Red color

B --> in Blue color

C --> in Green color

D --> in Yellow color

You can use a IValueConverter in your Binding

public class StringToColorConverter : IValueConverter
    {

        #region IValueConverter implementation

        public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is string && value != null)  {
                string s = (string)value;
                switch(s){
                    case "A":
                        return Color.Red;
                    case "B":
                        return Color.Blue;
                    default:
                        return Color.Black
                }

            }
            return Color.Black;
        }

        public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException ();
        }

        #endregion
    }

usage in xaml: add the namespace:

xmlns:local="clr-namespace:Meditation;assembly=Meditation"

create and add to your page StaticResources:

<ContentPage.Resources>
        <ResourceDictionary>
            <local: StringToColorConverter x:Key="cnvInvert"></local: StringToColorConverter >
        </ResourceDictionary>
        </ContentPage.Resources>

add to your binding:

<Label VerticalOptions="End" HorizontalOptions="Center" TextColor="{Binding ., Converter={StaticResource cnvInvert}}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM