首先,實作ICompare接口
public class ObjectPropertyCompare<T> : IComparer<T> {
private PropertyDescriptor property;
private ListSortDirection direction;
// 構造函數
public ObjectPropertyCompare(PropertyDescriptor property, ListSortDirection direction) {
this.property = property;
this.direction = direction;
}
// 實作IComparer中方法
public int Compare(T x, T y) {
object xValue = x.GetType().GetProperty(property.Name).GetValue(x, null);
object yValue = y.GetType().GetProperty(property.Name).GetValue(y, null);
int returnValue;
if (xValue is IComparable) {
returnValue = ((IComparable)xValue).CompareTo(yValue);
} else if (xValue.Equals(yValue)) {
returnValue = 0;
} else {
returnValue = xValue.ToString().CompareTo(yValue.ToString());
if (direction == ListSortDirection.Ascending) {
return returnValue;
return returnValue * -1;
然後建立自定義的類,實作IBindingList接口,為友善起見,這裡直接繼承BindingList類
/// <summary>
/// 自定義綁定清單類
/// </summary>
/// <typeparam name="T">清單對象類型</typeparam>
public class BindingCollection<T> : BindingList<T> {
private bool isSorted;
private PropertyDescriptor sortProperty;
private ListSortDirection sortDirection;
/// 構造函數
public BindingCollection()
: base() {
/// <param name="list">IList類型的清單對象</param>
public BindingCollection(IList<T> list)
: base(list) {
/// 自定義排序操作
/// <param name="property"></param>
/// <param name="direction"></param>
protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction) {
List<T> items = this.Items as List<T>;
if (items != null) {
ObjectPropertyCompare<T> pc = new ObjectPropertyCompare<T>(property, direction);
items.Sort(pc);
isSorted = true;
isSorted = false;
sortProperty = property;
sortDirection = direction;
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
/// 擷取一個值,訓示清單是否已排序
protected override bool IsSortedCore {
get {
return isSorted;
/// 擷取一個值,訓示清單是否支援排序
protected override bool SupportsSortingCore {
return true;
/// 擷取一個隻,指定類别排序方向
protected override ListSortDirection SortDirectionCore {
return sortDirection;
/// 擷取排序屬性說明符
protected override PropertyDescriptor SortPropertyCore {
return sortProperty;
/// 移除預設實作的排序
protected override void RemoveSortCore() {
建立BindingCollection後即可直接應用:
原來的方式是:
IList<object> list = new List<object>();
...
dataGridView.DataSource = list;
現在隻需更改最後一句為:
dataGridView.DataSource = new BindingCollection<object>(list);
即可