Нужно сделать свою сортировку в определенном столбце DataGrid
.
Данные берутся из ObservableCollection
. Столбец содержит строки. Нужно чтобы по клику в заголовке сортировало в том порядке, в котором нужно мне.
Все способы которые пытался найти просто описывают, как сортировать, по возрастанию или по убыванию, ну или я не разобрался. Вот пример
Скрестил бульдога с носорогом, возможно не совсем корректно и по другим столбцам сортировка не работает, но пока устраивает. upd: универсально сделать не получается, доработал под свои объекты.
DataGridDevices.Sorting += new DataGridSortingEventHandler(SortHandler);
void SortHandler(object sender, DataGridSortingEventArgs e)
{
var dg = sender as DataGrid;
DataGridColumn column = e.Column;
string dataGridHeaderIP = Globals.DataGridHeaderIP;
if (column.Header.ToString() == dataGridHeaderIP)
{
IComparer comparer = null;
// prevent the built-in sort from sorting
e.Handled = true;
ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
//set the sort order on the column
column.SortDirection = direction;
//use a ListCollectionView to do the sort.
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg.ItemsSource);
//this is my custom sorter it just derives from IComparer and has a few properties
//you could just apply the comparer but i needed to do a few extra bits and pieces
comparer = new SortIPAddress(direction);
//apply the sort
lcv.CustomSort = comparer;
}
}
public class SortIPAddress : IComparer
{
private readonly ListSortDirection direction;
public SortIPAddress(ListSortDirection direction)
{
this.direction = direction;
}
int IComparer.Compare(object x, object y)
{
string xIp = "";
string yIp = "";
long nX = 0;
long nY = 0;
if (x is Device && y is Device)
{
xIp = ((Device)x).Ip;
yIp = ((Device)y).Ip;
}
else if (x is Event && y is Event)
{
xIp = ((Event)x).Ip;
yIp = ((Event)y).Ip;
}
if (xIp != string.Empty && yIp != string.Empty)
{
string[] octetsX = xIp.Split('.');
string[] octetsY = yIp.Split('.');
if (octetsX.Count() == 4 && octetsY.Count() == 4)
{
nX = long.Parse(octetsX[0]) * 255 * 255 * 255 + long.Parse(octetsX[1]) * 255 * 255 + long.Parse(octetsX[2]) * 255 + long.Parse(octetsX[3]);
nY = long.Parse(octetsY[0]) * 255 * 255 * 255 + long.Parse(octetsY[1]) * 255 * 255 + long.Parse(octetsY[2]) * 255 + long.Parse(octetsY[3]);
}
}
if (direction == ListSortDirection.Ascending)
{
return MyCompare(nX, nY);
}
return MyCompare(nX, nY) * -1;
}
int MyCompare(long x, long y)
{
if (x == y)
{
return 0;
}
if (x > y)
{
return 1;
}
return -1;
}
}
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
Стратегії та тренди в SMM - Технології, що формують майбутнє сьогодні
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
yii2-advanced, суть: получаю $id, нахожу в таблице product_image 'id' => $id, и также надо найти запись из таблицы product, у которой должно быть 'id' => 'product_image->id'Найти...