假设我有以下值,我正在加载到数据网格中
ID | Desc
------------------------
32 Red Cat
33 Blue Dog
34 Red Dog
37 Green Zebra
42 Reddish Snake
47 Greenlike Gorilla
我想按描述中指定的起始颜色对数据网格上的值进行分组。所以会是这样的
ID | Desc
----------------------------
Red:
32 Red Cat
34 Red Dog
42 Reddish Snake
Blue:
33 Blue Dog
Green:
37 Green Zebra
47 Greenlike Gorilla
我为我的代码提供了这个:
PagedCollectionView pageView = new PagedCollectionView(IEnumerable<MyClass> main);
pageView.GroupDescriptions.Add(new PropertyGroupDescription("")); //?????
this.MyGrid.ItemsSource = pageView;
如何指定分组参数?
您可以提供对组描述的IValueConverter
。 所以使用:
new PropertyGroupDescription("Color", new StringToColorConverter())
其中 StringToColorConverter 将 Desc 属性转换为颜色字符串:
public class StringToColorConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((string)value == null) return null;
return ((string)value).Split(new [] { ' ' }).FirstOrDefault();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
替代方法
如果能够修改类,则可以添加一个简单的派生属性Color
。
class MyClass
{
public string Desc { get; set; }
public int ID { get; set; }
public string Color
{
get
{
return Desc.Split(new [] { ' ' }).FirstOrDefault();
}
}
}
然后,您可以对其进行分组。
new PropertyGroupDescription("Color")
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 方法中,您还可以使用字典将"奇怪的"颜色值映射到已知颜色值:
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;
}