[英]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我有一个字符串列表,它以 xamarin 形式分配给列表视图,如下面的代码
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 A --> 红色
B --> in Blue color B --> 蓝色
C --> in Green color C --> 绿色
D --> in Yellow color D --> 黄色
You can use a IValueConverter in your Binding您可以在绑定中使用 IValueConverter
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: xaml 中的用法:添加命名空间:
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}}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.