我有一个字符串列表,它被分配到xamarin表单中的listview,如下面的代码
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;
如何以不同颜色显示所有listview项目文本?我想像这样展示:
A - &gt;红色
B - &gt;蓝色
C - &gt;绿色
D - &gt;黄色的
答案 0 :(得分:3)
您可以在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
}
在xaml中的用法: 添加命名空间:
xmlns:local="clr-namespace:Meditation;assembly=Meditation"
创建并添加到您的页面StaticResources:
<ContentPage.Resources>
<ResourceDictionary>
<local: StringToColorConverter x:Key="cnvInvert"></local: StringToColorConverter >
</ResourceDictionary>
</ContentPage.Resources>
添加到您的绑定:
<Label VerticalOptions="End" HorizontalOptions="Center" Text="{Binding ., Converter={StaticResource cnvInvert}}">