2010/06/09(Wed) 19:32:20 編集(投稿者)
以下のような感じでどうでしょうか。
※ 文字列にしか対応させてません
List<MyClass> list = getList();
dataGridView1.DataSource = new MyClassSortList<MyClass>(list);
.........
class MyClassComparer<T> : IComparer<T> {
private ListSortDirection direction;
private PropertyDescriptor prop;
public MyClassComparer(PropertyDescriptor prop, ListSortDirection direction) {
this.prop = prop;
this.direction = direction;
}
public int Compare(T x, T y) {
object objX = x.GetType().GetProperty(prop.Name).GetValue(x, null);
object objY = y.GetType().GetProperty(prop.Name).GetValue(y, null);
int ret = objX.ToString().CompareTo(objY.ToString()); // とりあえず文字列のみ。。。
if ((direction == ListSortDirection.Descending)) {
ret *= -1;
}
return ret;
}
}
class MyClassSortList<T> : BindingList<T> {
public MyClassSortList(List<T> list) {
((List<T>)Items).AddRange(list);
}
protected override bool SupportsSortingCore {
get { return true; }
}
protected override void ApplySortCore(PropertyDescriptor propDescriptor
, ListSortDirection listDirection) {
List<T> list = (List<T>)base.Items;
if (list != null) {
MyClassComparer<T> comparer = new MyClassComparer<T>(propDescriptor, listDirection);
list.Sort(comparer);
}
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemMoved, propDescriptor));
}
}