Своя сортировка в DataGrid WPF

191
04 января 2019, 13:30

Нужно сделать свою сортировку в определенном столбце DataGrid. Данные берутся из ObservableCollection. Столбец содержит строки. Нужно чтобы по клику в заголовке сортировало в том порядке, в котором нужно мне.

Все способы которые пытался найти просто описывают, как сортировать, по возрастанию или по убыванию, ну или я не разобрался. Вот пример

Answer 1

Скрестил бульдога с носорогом, возможно не совсем корректно и по другим столбцам сортировка не работает, но пока устраивает. 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;
    }
}
READ ALSO
Тень для Panel Windows Forms

Тень для Panel Windows Forms

Подскажите как сделать тень для Panel/GroupBox

340
YII2 Как правильно построить запрос с joinWith?

YII2 Как правильно построить запрос с joinWith?

yii2-advanced, суть: получаю $id, нахожу в таблице product_image 'id' => $id, и также надо найти запись из таблицы product, у которой должно быть 'id' => 'product_image->id'Найти...

253
как записать массив в базу данных

как записать массив в базу данных

Имеется массив вида

216