【问题标题】:how to give different text color for each item of listview in xamarin forms如何在 xamarin 表单中为列表视图的每个项目提供不同的文本颜色
【发布时间】:2017-04-07 15:05:14
【问题描述】:

我有一个字符串列表,它被分配给 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;

如何以不同颜色显示所有列表视图项文本?我想像这样展示它:

A --> 红色

B --> 蓝色

C --> 绿色

D --> 黄色

【问题讨论】:

    标签: c# listview xamarin xamarin.forms


    【解决方案1】:

    您可以在 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"
    

    创建并添加到您的页面静态资源:

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

    添加到您的绑定中:

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

    【讨论】:

    • 对不起,我是 Xamarin 的新手。你能告诉我我需要在哪里实施吗?我把它放在同一个 mypage.xaml.cs 文件中。但它仍然无法正常工作。
    • 你能发布你的 xaml 吗?
    • xamarin.com/schemas/2014/forms" xmlns:x="schemas.microsoft.com/winfx/2009/xaml" x:Class="Srd.工作" Title="Jobs" BackgroundColor="#caccce">
    • .xaml.cs 文件` [XamlCompilation(XamlCompilationOptions.Compile)] public partial class mypage: ContentPage { public mypage(List jobList) { InitializeComponent(); ListView listview = new ListView(); listview.ItemsSource = 工作清单;内容=列表视图; } }`
    • 这有点复杂。您已经开始使用 XAML,因此您应该在 Xaml 中添加您的 ListView,在 Xaml 中创建一个 ViewCell 并在 Xaml 中添加标签...看看这个developer.xamarin.com/guides/xamarin-forms/user-interface/…
    猜你喜欢
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多