PropertyGroupDescription 只是GroupDescription的一种实现。你可以自己滚动。事实上,我们可以为一般目的滚动一个:
public class LambdaGroupDescription<T> : GroupDescription
{
public Func<T, object> GroupDelegate { get; set; }
public LambdaGroupDescription(Func<T, object> groupDelegate)
{
this.GroupDelegate = groupDelegate;
}
public override object GroupNameFromItem(object item, int level, System.Globalization.CultureInfo culture)
{
return this.GroupDelegate((T)item);
}
}
然后将其添加到 PagedCollectionView:
var pageView = new PagedCollectionView(items);
pageView.GroupDescriptions.Add(new LambdaGroupDescription<ViewModel>(
vm => vm.Description.Split(' ').FirstOrDefault()
));
this.DataGrid.ItemsSource = pageView;
编辑
看来您的分组逻辑比简单的拆分要复杂一些。您可以尝试以下方法:
public string FormatColor(string color)
{
if (string.IsNullOrWhiteSpace(color)) return null;
if (color.ToUpperInvariant().StartsWith("RED"))
return "Red";
if (color.ToUpperInvariant().StartsWith("GREEN"))
return "Green";
return color;
}
进而:
pageView.GroupDescriptions.Add(new LambdaGroupDescription<ViewModel>(
vm => FormatColor(vm.Description.Split(' ').FirstOrDefault() as string)
));
在 FormatColor 方法中,您还可以使用 Dictionary 将“奇怪”颜色值映射到已知颜色值:
private static readonly Dictionary<string, string> ColorMap = new Dictionary<string, string>(){
{"Greenlike", "Green"},
{"Reddish", "Red"},
};
public string FormatColor(string color)
{
if (string.IsNullOrWhiteSpace(color)) return null;
if (ColorMap.ContainsKey(color))
return ColorMap[color];
return color;
}