基于DateTime创建自定义GroupDescription

Ing*_*als 2 wpf grouping datetime groupstyle

我正在对一些数据进行分组,并且PropertyGroupDescription在大多数情况下都能正常工作。但是,如果该属性是DateTime,并且我不想将多个日期作为一个组一起分组(例如每个组中30天左右),则需要一个新的GroupDescription。问题是我不知道该类的实际工作方式以及如何设计此类。

我希望能够继承PropertyGroupDescription(而不是基本的抽象类),因为这也将基于属性,但是在这里,我基于一系列值而不是单个值== 1组进行分组。

有任何指导甚至是这样的准备班吗?

Jac*_*eka 5

有点晚了,但是正如您所说的,您IValueConverter可以使用它-这是我使用过的一个简单转换器,它将按友好的相对日期字符串分组:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以像这样使用它:

view.GroupDescriptions.Add(
    new PropertyGroupDescription("Property", 
        new RelativeDateValueConverter()));
Run Code Online (Sandbox Code Playgroud)