我想根据日期更改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
}
}
正如 Jason 建议的,您可以 Converter 根据日期将类型转换为
Color
。
我做了一个demo,效果很好,你可以参考一下:
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;
}
}
<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;
}
MyItem.cs
public class MyItem
{
public DateTime ExpiryDate { get; set; }
}