Creating custom GroupDescription based on DateTime

孤人 提交于 2019-12-10 11:29:58

问题


I'm grouping some data and PropertyGroupDescription works fine most of the time. However if that property is a DateTime and i wan't to group several dates together as one group (like 30 days in each group or something) I would need a new GroupDescription. Problem is I have no idea how the class actually works and how I would design such a class.

I'm hoping to be able to inherit PropertyGroupDescription (instead of the basic abstract class) because this will also be based on a property but here I'm grouping based on a range of values instead of a single value == 1 group.

Any guide or even a ready class like this?


回答1:


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()));


来源:https://stackoverflow.com/questions/6423738/creating-custom-groupdescription-based-on-datetime

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