Reputation: 5315
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
Upvotes: 1
Views: 5806
Reputation: 5768
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}}">
Upvotes: 6