Learning/Mysql-example/Util/SortableBindingList.cs
2023-05-05 20:58:11 +02:00

93 lines
2.9 KiB
C#

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<T> : BindingList<T>
{
private bool IsSorted { get; set; }
private ListSortDirection SortDirection { get; set; }
private PropertyDescriptor SortProperty { get; set; }
private readonly List<T>? _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<T> items = Items as List<T>;
if (items is null)
{
IsSorted = false;
}
else
{
var PCom = new PCompare<T>(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<T> list) : base((IList<T>)list)
{
}
public SortableBindingList() : base()
{
}
#endregion
#region Property comparer
private class PCompare<Type> : IComparer<T> 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<T>.Compare(T x, T y) => Compare(x, y);
}
#endregion
}
}