using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Mysql_example.Util { public class SortableBindingList : BindingList { private bool IsSorted { get; set; } private ListSortDirection SortDirection { get; set; } private PropertyDescriptor SortProperty { get; set; } private readonly List? _originalData; protected override bool SupportsSortingCore { get { return true; } } protected override ListSortDirection SortDirectionCore { get { return SortDirection; } } protected override PropertyDescriptor SortPropertyCore { get { return SortProperty; } } protected override void ApplySortCore(PropertyDescriptor PDsc, ListSortDirection Direction) { List items = Items as List; if (items is null) { IsSorted = false; } else { var PCom = new PCompare(PDsc.Name, Direction); items.Sort(PCom); IsSorted = true; SortDirection = Direction; SortProperty = PDsc; } OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); } protected override bool IsSortedCore { get { return IsSorted; } } protected override void RemoveSortCore() { IsSorted = false; } #region Constructors public SortableBindingList(ICollection list) : base((IList)list) { } public SortableBindingList() : base() { } #endregion #region Property comparer private class PCompare : IComparer where Type : T { private PropertyInfo PropInfo { get; set; } private ListSortDirection SortDir { get; set; } internal PCompare(string SortProperty, ListSortDirection SortDirection) { PropInfo = typeof(T).GetProperty(SortProperty); SortDir = SortDirection; } internal int Compare(T x, T y) { return SortDir == ListSortDirection.Ascending ? Comparer.Default.Compare(PropInfo.GetValue(x, null), PropInfo.GetValue(y, null)) : Comparer.Default.Compare(PropInfo.GetValue(y, null), PropInfo.GetValue(x, null)); } int IComparer.Compare(T x, T y) => Compare(x, y); } #endregion } }