SortableBindingList.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. namespace CLIP.eForm.Consent.UI
  6. {
  7. public class SortableBindingList<T> : BindingList<T>
  8. {
  9. private bool isSortedValue;
  10. ListSortDirection sortDirectionValue;
  11. PropertyDescriptor sortPropertyValue;
  12. public SortableBindingList()
  13. {
  14. }
  15. public SortableBindingList(IList<T> list)
  16. {
  17. foreach (object o in list)
  18. {
  19. this.Add((T)o);
  20. }
  21. }
  22. protected override void ApplySortCore(PropertyDescriptor prop,
  23. ListSortDirection direction)
  24. {
  25. Type interfaceType = prop.PropertyType.GetInterface("IComparable");
  26. if (interfaceType == null && prop.PropertyType.IsValueType)
  27. {
  28. Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);
  29. if (underlyingType != null)
  30. {
  31. interfaceType = underlyingType.GetInterface("IComparable");
  32. }
  33. }
  34. if (interfaceType != null)
  35. {
  36. sortPropertyValue = prop;
  37. sortDirectionValue = direction;
  38. IEnumerable<T> query = base.Items;
  39. if (direction == ListSortDirection.Ascending)
  40. {
  41. query = query.OrderBy(i => prop.GetValue(i));
  42. }
  43. else
  44. {
  45. query = query.OrderByDescending(i => prop.GetValue(i));
  46. }
  47. int newIndex = 0;
  48. foreach (object item in query)
  49. {
  50. this.Items[newIndex] = (T)item;
  51. newIndex++;
  52. }
  53. isSortedValue = true;
  54. this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
  55. }
  56. else
  57. {
  58. throw new NotSupportedException("Cannot sort by " + prop.Name +
  59. ". This" + prop.PropertyType.ToString() +
  60. " does not implement IComparable");
  61. }
  62. }
  63. protected override PropertyDescriptor SortPropertyCore
  64. {
  65. get { return sortPropertyValue; }
  66. }
  67. protected override ListSortDirection SortDirectionCore
  68. {
  69. get { return sortDirectionValue; }
  70. }
  71. protected override bool SupportsSortingCore
  72. {
  73. get { return true; }
  74. }
  75. protected override bool IsSortedCore
  76. {
  77. get { return isSortedValue; }
  78. }
  79. }
  80. }