Добавил сортировку BindingList(), почему не работает?
Я новичок в этом, мог ошибиться с кодом для сортировки BindingList(), буду безумно благодарен если рабочий код. Код показывает таблицу в DataGrid, но по нажатию на заголовки не сортирует по имени. Ошибок нигде никаких не выдает, все в норме. Код запускается, но не сортирует.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace DOCTORSGUIDE
{
/// <summary>
/// Provides a generic collection that supports data binding and additionally supports sorting.
/// See http://msdn.microsoft.com/en-us/library/ms993236.aspx
/// If the elements are IComparable it uses that; otherwise compares the ToString()
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
[Serializable]
public class SortableBindingList<Model> : BindingList<Model>
{
private bool _isSorted;
private ListSortDirection _sortDirection = ListSortDirection.Ascending;
private PropertyDescriptor _sortProperty;
/// <summary>
/// Gets a value indicating whether the list supports sorting.
/// </summary>
protected override bool SupportsSortingCore
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the list is sorted.
/// </summary>
protected override bool IsSortedCore
{
get { return _isSorted; }
}
/// <summary>
/// Gets the direction the list is sorted.
/// </summary>
protected override ListSortDirection SortDirectionCore
{
get { return _sortDirection; }
}
/// <summary>
/// Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class; otherwise, returns null
/// </summary>
protected override PropertyDescriptor SortPropertyCore
{
get { return _sortProperty; }
}
/// <summary>
/// Removes any sort applied with ApplySortCore if sorting is implemented
/// </summary>
protected override void RemoveSortCore()
{
_sortDirection = ListSortDirection.Ascending;
_sortProperty = null;
}
/// <summary>
/// Sorts the items if overridden in a derived class
/// </summary>
/// <param name="prop"></param>
/// <param name="direction"></param>
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
_sortProperty = prop;
_sortDirection = direction;
if (_sortProperty == null) return; //nothing to sort on
List<Model> list = Items as List<Model>;
if (list == null) return;
list.Sort(delegate (Model lhs, Model rhs)
{
object lhsValue = lhs == null ? null : _sortProperty.GetValue(lhs);
object rhsValue = rhs == null ? null : _sortProperty.GetValue(rhs);
int result = 0;
if (lhsValue == null && rhsValue == null)
{
result = 0;
}
else if (lhsValue == null)
{
result = -1;
}
else if (rhsValue == null)
{
result = 1;
}
else
{
if (lhsValue is IComparable)
{
result = ((IComparable)lhsValue).CompareTo(rhsValue);
}
else if (!lhsValue.Equals(rhsValue))//not comparable, compare ToString
{
result = lhsValue.ToString().CompareTo(rhsValue.ToString());
}
}
if (_sortDirection == ListSortDirection.Descending)
result = -result;
return result;
});
_isSorted = true;
//fire an event that the list has been changed.
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
public static implicit operator List<Model>(SortableBindingList<Model> sortableBindingList)
{
return sortableBindingList.Items.ToList();
}
}
}
private readonly string Path = $"{Environment.CurrentDirectory}\\Dannie.json";
private BindingList<Model> Dannie;
private SaveFile saveFile;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
saveFile = new SaveFile(Path);
try
{
Dannie = saveFile.Load();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //если ошибка, приложение закрывается
Close();
}
DataGridView1.ItemsSource = Dannie;
Dannie.ListChanged += Dannie_ListChanged;
}
private void Dannie_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded || e.ListChangedType == ListChangedType.ItemDeleted || e.ListChangedType == ListChangedType.ItemChanged)
{
try
{
saveFile.Save(sender);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //если ошибка, приложение закрывается
Close();
}
}
}
<DataGrid x:Name="DataGridView1" FontWeight="Bold" FontSize="16" Margin="0,34,8,119" AutoGenerateColumns="False" CanUserSortColumns="True" CanUserResizeColumns="False" CanUserReorderColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" IsReadOnly="True" IsTextSearchEnabled="True" Grid.Column="1" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path = Namee}" Header="Name" Width="145" />
<DataGridTextColumn Binding="{Binding Path = Symptoms}" Header="Symptoms" Width="145" />
<DataGridTextColumn Binding="{Binding Path = Procedures}" Header="Procedures" Width="145" />
<DataGridTextColumn Binding="{Binding Path = Recommended}" Header="Recommended medicines" Width="*" />
</DataGrid.Columns>
</DataGrid>