开发者

Creating custom GroupDescription based on DateTime

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 al开发者_StackOverflow社区so 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜