在WinForms中,ListView控件支持多列排序
using System.Windows.Forms;
using System.Collections;
public class MultiColumnSortableListView : ListView
{
private ArrayList _columnSorters;
public MultiColumnSortableListView()
{
_columnSorters = new ArrayList();
}
// ... 其他代码
}
public void AddColumnSorter(int columnIndex, IComparer comparer)
{
if (_columnSorters.Count <= columnIndex)
{
_columnSorters.Capacity = columnIndex + 1;
}
_columnSorters[columnIndex] = comparer;
}
public override IComparer ListViewItemSorter
{
get
{
return new MultiColumnComparer(_columnSorters);
}
set
{
base.ListViewItemSorter = value;
}
}
internal class MultiColumnComparer : IComparer
{
private ArrayList _columnSorters;
public MultiColumnComparer(ArrayList columnSorters)
{
_columnSorters = columnSorters;
}
public int Compare(object x, object y)
{
ListViewItem itemX = (ListViewItem)x;
ListViewItem itemY = (ListViewItem)y;
for (int i = 0; i < _columnSorters.Count; i++)
{
IComparer comparer = (IComparer)_columnSorters[i];
if (comparer != null)
{
int result = comparer.Compare(itemX.SubItems[i].Text, itemY.SubItems[i].Text);
if (result != 0)
{
return result;
}
}
}
return 0;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 添加列比较器
multiColumnSortableListView1.AddColumnSorter(0, StringComparer.CurrentCulture);
multiColumnSortableListView1.AddColumnSorter(1, new NumericComparer());
}
}
private void multiColumnSortableListView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
multiColumnSortableListView1.Sorting = multiColumnSortableListView1.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
multiColumnSortableListView1.Sort();
}
现在,当用户单击列标题时,ListView控件将根据添加的多列比较器进行排序。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。