如何根据Xamarin表单中collectionView中的值更改行背景颜色

问题描述 投票:0回答:1

我想根据日期更改collectionView中背景行的颜色。

例如:

foreach(var item in myList) 
{
    if (item.ExpiryDate <= DateTime.Now )
    {
        Mylistrow.BackgroundColor = Color.Coral
    }
    else if (item.ExpiryDate > DateTime.Now.AddMonth(3))
    {
        Mylistrow.BackgroundColor = Color.Orange
    }
}
xamarin.forms
1个回答
0
投票

正如 Jason 建议的,您可以 Converter 根据日期将类型转换为

Color

我做了一个demo,效果很好,你可以参考一下:

  1. 创建IValueConverter:DateColorConverter.cs:
    public class DateColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (((DateTime)value).Date <= DateTime.Now.Date) return Color.Coral;

            else if ( ((DateTime)value).Date > DateTime.Now.AddMonths(3) ) return Color.Orange;

            return Color.Default;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

  1. XAML
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:DateColorConverter x:Key="DateColor" />
        </ResourceDictionary>
    </ContentPage.Resources>


    <CollectionView ItemsSource="{Binding Items}">
        <CollectionView.ItemTemplate >
            <DataTemplate x:DataType="local:MyItem">
                <Grid BackgroundColor="{Binding ExpiryDate,Converter={StaticResource DateColor}}">
                    <Label Text="{Binding ExpiryDate}"></Label>
                </Grid>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

代码隐藏

public ObservableCollection<MyItem> Items { get; set; }
public MainPage()
{
      InitializeComponent();

      Items = new ObservableCollection<MyItem>() {       
      new MyItem{ExpiryDate=DateTime.Now.AddMonths(4)},
      new MyItem{ExpiryDate=DateTime.Now.AddMonths(4)},
      new MyItem{ExpiryDate=DateTime.Now},
      new MyItem{ExpiryDate=DateTime.Now},
};

     BindingContext = this;
}

  1. 模式类:
    MyItem.cs
public class MyItem
{
    public DateTime ExpiryDate { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.