Xamarin如何在listview中设置不同的行颜色

Xamarin如何在listview中设置不同的行颜色,listview,xamarin,Listview,Xamarin,我试图在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="#f3

我试图在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
字段。如果
Active
false
BackgroundColor
设置为红色。如果
true
BackgroundColor
设置为绿色


我怎么做?谢谢。

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

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}}" />

非常感谢。效果很好。P.S.在背景色中绑定属性后应为昏迷状态。