Xamarin在ListView中更改每个ViewCell的背景色

Xamarin在ListView中更改每个ViewCell的背景色,listview,xamarin,xamarin.forms,background-color,Listview,Xamarin,Xamarin.forms,Background Color,我在listView中有预约时间,如8:00、9:00等。通过JSON,我从远程数据库检索已经做出的预约。因此,我想将每个单元格(标签)的背景颜色更改为保留的红色,其余的更改为绿色(免费约会) 这是我的xaml代码: <StackLayout> <ListView x:Name="ItemsListView" ItemsSource="{Binding Items}" VerticalOptions="FillAn

我在listView中有预约时间,如8:00、9:00等。通过JSON,我从远程数据库检索已经做出的预约。因此,我想将每个单元格(标签)的背景颜色更改为保留的红色,其余的更改为绿色(免费约会)

这是我的xaml代码:

    <StackLayout>
    <ListView x:Name="ItemsListView"
            ItemsSource="{Binding Items}"
            VerticalOptions="FillAndExpand"
            HasUnevenRows="true"
            RefreshCommand="{Binding LoadItemsCommand}"
            IsPullToRefreshEnabled="true"
            IsRefreshing="{Binding IsBusy, Mode=OneWay}"
            CachingStrategy="RecycleElement"
            ItemSelected="OnItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Padding="10">
                        <Label Text="{Binding Text}" 
                            LineBreakMode="NoWrap" 
                            Style="{DynamicResource ListItemTextStyle}" 
                            FontSize="16" />

                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>
那么我怎样才能改变这些细胞的颜色呢

我想要的伪代码:

for(int i=0; i< number of items in the listview; i++) {
if(reservations.contains(listview.itemAt(i)) {
//change background color of viewcell (label?) at position i
}
}
for(int i=0;i
(正如布鲁诺评论的那样)

IsReserved
布尔属性添加到模型中: 如果
IsReserved
为真,则返回
Red
IValueConverter
: 添加IValueConverter的命名空间: 将IValueConverter添加到ContentPage。参考资料
您可以使用自定义视图单元格。我在项目中编写了一个自定义视图单元格,并使用了XFGloss(XFGloss是Xamarin.Forms项目的一个附加组件,用于向标准XF页面和控件类添加新属性)使listView的行丰富多彩。您的listView不会丢失XFGloss的触觉反馈。我使用的自定义viewCell是:

 public class MyViewCell : ViewCell
    {
        private Color BackgroundColor
        {
            get => CellGloss.GetBackgroundColor(this);
            set => CellGloss.SetBackgroundColor(this, value);
        }

        public Color EvenColor { get; set; }
        public Color UnevenColor { get; set; }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            if (!(Parent is ListView listView))
                throw new Exception(
                    $"The Binding Context is not {typeof(ListView)}. This component works only with {typeof(ListView)}.");

            int index;
            if (listView.IsGroupingEnabled)
            {
                index = listView.TemplatedItems.GetGroupAndIndexOfItem(BindingContext).Item2;
            }
            else
            {
                index = listView.TemplatedItems.IndexOf(this);
            }

            if (index != -1)
                BackgroundColor = index % 2 == 0 ? EvenColor : UnevenColor;
        }
    }
它在xaml文件中的用法很简单,如下所示:

<components:MyViewCell EvenColor="White" UnevenColor="#eeeeee">


如果您更改模型以保留属性,会更容易。例如,在Listview viewcell中,您只需使用一个转换器来更改颜色。我太新手了,无法理解您所说的一半内容。谢谢您提供的详细答案,您的代码显然有效。@ChrisFodor很高兴有什么方法可以代替指定使用IvalueConverter的颜色仅用于将其作为参数传递?例如=IsReserved=true,color red;。要能够将不同的颜色传递给帧?@Pxaml当然,您可以将属性指定为实际颜色(color.red等),或者使用绑定参数并传递颜色:
public class IsReservedToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((bool)value ? Color.Red : Color.Transparent);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
xmlns:local="clr-namespace:SameNameSpace;assembly=SomeAssemblyName"   
<ContentPage.Resources>
    <ResourceDictionary>
        <local:IsReservedToColorConverter x:Key="IsReservedToColor"></local:IsReservedToColorConverter>
    </ResourceDictionary>
</ContentPage.Resources>
<Frame BackgroundColor = "{Binding IsReserved, Converter={StaticResource IsReservedToColor}}">
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms"  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Forms_31_1.ListPage"
    xmlns:local="clr-namespace:Forms_31_1;assembly=Forms_31_1" >
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IsReservedToColorConverter x:Key="IsReservedToColor"></local:IsReservedToColorConverter>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ListView x:Name="listView" BackgroundColor="Aqua" SeparatorColor="Red">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame BackgroundColor = "{Binding IsReserved, Converter={StaticResource IsReservedToColor}}">
                            <StackLayout Orientation="Vertical">
                                <Label Text="{Binding Text}" />
                                <Label Text="{Binding Description}" />
                            </StackLayout>
                        </Frame>
                </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "11:00" });
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "12:00", IsReserved = true });
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "13:00" });
posts.Add(new Termin { Id = Guid.NewGuid().ToString(), Text = "14:00" });
 public class MyViewCell : ViewCell
    {
        private Color BackgroundColor
        {
            get => CellGloss.GetBackgroundColor(this);
            set => CellGloss.SetBackgroundColor(this, value);
        }

        public Color EvenColor { get; set; }
        public Color UnevenColor { get; set; }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            if (!(Parent is ListView listView))
                throw new Exception(
                    $"The Binding Context is not {typeof(ListView)}. This component works only with {typeof(ListView)}.");

            int index;
            if (listView.IsGroupingEnabled)
            {
                index = listView.TemplatedItems.GetGroupAndIndexOfItem(BindingContext).Item2;
            }
            else
            {
                index = listView.TemplatedItems.IndexOf(this);
            }

            if (index != -1)
                BackgroundColor = index % 2 == 0 ? EvenColor : UnevenColor;
        }
    }
<components:MyViewCell EvenColor="White" UnevenColor="#eeeeee">