假设我有以下值,我正在加载到数据网格
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;
我如何指定分组参数?
答案 0 :(得分:1)
You can provide an IValueConverter
到GroupDescription。所以使用:
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")
答案 1 :(得分:0)
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;
}