我在 C# WinForms 应用程序中使用 ListView 控件。列表中的项目被添加到 ListViewGroup(在这种情况下,按国家/地区分组)。没有按预期工作的一件事是列排序似乎很奇怪。
我已经连接到 ListView 的 ListViewItemSorter 属性,并且除了国家列按降序(即 ZA)排序时,所有内容都排序完美。无论列表排序如何发生,组都以升序显示。
任何人都可以在正确的方向上轻推我吗?
编辑:FWIW,Vista 上的 .NET 3.5。
在您的 ColumnClick 事件中尝试一下:
// Determine whether the column is the same as the last column clicked.
if (e.Column != sortColumn)
{
// Set the sort column to the new column.
sortColumn = e.Column;
// Set the sort order to ascending by default.
listView1.Sorting = SortOrder.Ascending;
}
else
{
// Determine what the last sort order was and change it.
if (listView1.Sorting == SortOrder.Ascending)
listView1.Sorting = SortOrder.Descending;
else
listView1.Sorting = SortOrder.Ascending;
}
// Call the sort method to manually sort.
listView1.Sort();
// Set the ListViewItemSorter property to a new ListViewItemComparer
// object.
this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column,
listView1.Sorting);
Groups should be sorted separately
// save groups
ListViewGroup[] oGroups = new ListViewGroup[list.Groups.Count];
list.Groups.CopyTo(oGroups, 0);
list.Groups.Clear();
// restore groups
switch (groupSortOrder)
{
case SortOrder.Ascending:
list.Groups.AddRange(oGroups.OrderBy(x => x.Name).ToArray());
break;
case SortOrder.Descending:
list.Groups.AddRange(oGroups.OrderByDescending(x => x.Name).ToArray());
break;
default:
list.Groups.AddRange(oGroups);
break;
}
查看ObjectListView - 它更容易使用。