【问题标题】:Xamarin how to set diferent row color in listviewXamarin如何在listview中设置不同的行颜色
【发布时间】:2017-07-11 19:09:00
【问题描述】:

我正在尝试在 Xamarin 中创建一个 listView,其中行中的某些元素会根据对象中的值而有所不同。 例如。备注型号:

public class Note
{
    public string Title { get; set; }
    public string Content { get; set; }
    public bool Active { get; set; }
}

在 XAML 中:

<Label Text="{Binding Title}" TextColor="#f35e20" />
<Label Text="{Binding Content}" TextColor="#503026" />
<Button BackgroundColor="#000" />

我希望有按钮 BackgroundColor 取决于 Active 字段。如果Activefalse,则BackgroundColor 设置为红色。如果trueBackgroundColor 设置为绿色。

我该怎么做?谢谢。

【问题讨论】:

    标签: listview xamarin


    【解决方案1】:

    首先,制作一个值转换器,让您将颜色绑定到布尔值:

    using System;
    using Xamarin.Forms;
    using System.Globalization;
    
    namespace MyApp
    {
        public class BoolToColorConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                bool b = ((bool)value);
                return b ? Color.Green : Color.Red;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
    

    然后,将转换器导入您的 xaml 文件:

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

    将其添加到页面的资源字典中:

    <ContentPage.Resources>
      <ResourceDictionary>
        <local:BoolToColorConverter x:Key="boolToColorConverter"/>
      </ResourceDictionary>
    </ContentPage.Resources>
    

    然后你可以在你的绑定中使用它:

    <Label Text="{Binding Title}" TextColor="#f35e20" />
    <Label Text="{Binding Content}" TextColor="#503026" />
    <Button BackgroundColor="{Binding Active, Converter={StaticResource boolToColorConverter}}" />
    

    【讨论】:

    • 非常感谢。效果很好。附言BackgroundColor 中的 Binding 属性后应该是昏迷。
    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 2016-08-18
    • 2012-11-06
    相关资源
    最近更新 更多