Creating custom GroupDescription based on DateTime

强颜欢笑 提交于 2019-12-06 11:17:28

A bit late, but as you say yourself IValueConverter can be used for this - here's a simple converter I used once that will group by a friendly relative date string:

public class RelativeDateValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var v = value as DateTime?;
        if(v == null) {
            return value;
        }

        return Convert(v.Value);
    }

    public static string Convert(DateTime v)
    {
        var d = v.Date;
        var today = DateTime.Today;
        var diff = today - d;
        if(diff.Days == 0) {
            return "Today";
        }

        if(diff.Days == 1) {
            return "Yesterday";
        }

        if(diff.Days < 7) {
            return d.DayOfWeek.ToString();
        }

        if(diff.Days < 14) {
            return "Last week";
        }

        if(d.Year == today.Year && d.Month == today.Month) {
            return "This month";
        }

        var lastMonth = today.AddMonths(-1);
        if(d.Year == lastMonth.Year && d.Month == lastMonth.Month) {
            return "Last month";
        }

        if(d.Year == today.Year) {
            return "This year";
        }

        return d.Year.ToString(culture);
    }

    public static int Compare(DateTime a, DateTime b)
    {
        return Convert(a) == Convert(b) ? 0 : a.CompareTo(b);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

You can then use it like this:

view.GroupDescriptions.Add(
    new PropertyGroupDescription("Property", 
        new RelativeDateValueConverter()));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!