dmitriy Asked:2020-09-20 16:22:50 +0800 CST2020-09-20 16:22:50 +0800 CST 2020-09-20 16:22:50 +0800 CST DataGrid WPF 中的自定义排序 772 您需要在特定列中进行排序DataGrid。数据取自 ObservableCollection。该列包含行。有必要通过单击按我需要的顺序排序的标题。 我试图找到的所有方法都只是描述了如何按升序或降序排序,或者我没有弄明白。这是一个例子 c# 1 个回答 Voted Best Answer dmitriy 2020-09-20T19:17:21+08:002020-09-20T19:17:21+08:00 我用犀牛越过了斗牛犬,可能不太正确,并且在其他列上排序不起作用,但到目前为止它适合。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; } }
我用犀牛越过了斗牛犬,可能不太正确,并且在其他列上排序不起作用,但到目前为止它适合。upd:不可能通用,我为我的对象修改了它。