wpf - 基于 DateTime 创建自定义 GroupDescription

标签 wpf datetime grouping groupstyle

我正在对一些数据进行分组,而 PropertyGroupDescription 大多数时候都可以正常工作。但是,如果该属性是 DateTime,并且我不想将多个日期分组为一个组(例如每组 30 天之类),我将需要一个新的 GroupDescription。问题是我不知道这个类实际上是如何工作的,也不知道我将如何设计这样一个类。

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

是否有像这样的指南或准备好的类(class)?

最佳答案

有点晚了,但正如您自己所说,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();
    }
}

然后你可以像这样使用它:

view.GroupDescriptions.Add(
    new PropertyGroupDescription("Property", 
        new RelativeDateValueConverter()));

关于wpf - 基于 DateTime 创建自定义 GroupDescription,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423738/

相关文章:

c# - WPF 平铺背景(以像素为单位)

pandas - 有没有办法修复或绕过数据帧中特定列中奇怪的时间格式?

javascript - 需要帮助使用 lodash 来重组具有新结构的数组

listbox - WP7 列表框分组

wpf treeviewitem鼠标双击

c# - 模拟 MessageBox.Show()

c# - 图片源应用设置URI为根目录

powershell - 奇数日期/时间格式

php: datetime() 2 个日期时间与 2 个变量之间的差异

php - 根据两列值和每组中一列的总和对多维数组数据进行分组