65.9K
CodeProject 正在变化。 阅读更多。
Home

ListView 组排序器

starIconstarIconstarIconstarIconstarIcon

5.00/5 (9投票s)

2009 年 8 月 17 日

CPOL
viewsIcon

82031

downloadIcon

3786

一个易于使用的 ListView 分组排序器(非常简单)。

升序排序

降序排序

Desc.jpg

引言

这里的代码使您能够对 ListView 分组进行升序或降序排序。

背景

我需要一个“快速且简单的”解决方案来对 ListView 中的分组进行排序。所以我提出了这个非常非常简单的解决方案。

使用代码

只需将您的 ListView 转换为我的 ListView 包装器,然后调用 SortGroup(bool)

就像这样,其中 listView1 是您要排序的 ListView

((ListViewGroupSorter)listView1).SortGroups(true);  //Ascending...
((ListViewGroupSorter)listView1).SortGroups(false); //Descending...

ListViewGroupHeaderSorter 类

public class ListViewGroupHeaderSorter : IComparer<ListViewGroup>
{
    private bool _ascending = true;
    public ListViewGroupHeaderSorter(bool ascending)
    {
        _ascending = ascending;
    }

#region IComparer<ListViewGroup> Members

    public int Compare(ListViewGroup x, ListViewGroup y)
    {
    if (_ascending)
        return string.Compare(((ListViewGroup)x).Header, ((ListViewGroup)y).Header);
    else
        return string.Compare(((ListViewGroup)y).Header, ((ListViewGroup)x).Header);
    }
#endregion
}

ListViewGroupHeaderSorter 类

public class ListViewGroupSorter
{
    internal ListView _listview;

    public static bool operator ==(ListView listview, ListViewGroupSorter sorter)
    {
        return listview == sorter._listview;
    }
    public static bool operator !=(ListView listview, ListViewGroupSorter sorter)
    {
        return listview != sorter._listview;
    }

    public static implicit operator ListView(ListViewGroupSorter sorter)
    {
        return sorter._listview;
    }
    public static implicit operator ListViewGroupSorter(ListView listview)
    {
        return new ListViewGroupSorter(listview);
    }

    internal ListViewGroupSorter(ListView listview)
    {
        _listview = listview;
    }

    public void SortGroups(bool ascending)
    {
        _listview.BeginUpdate();
        List<listviewgroup> lvgs = new List<listviewgroup>();
        foreach (ListViewGroup lvg in _listview.Groups)
            lvgs.Add(lvg);
        _listview.Groups.Clear();
        lvgs.Sort(new ListViewGroupHeaderSorter(ascending));
        _listview.Groups.AddRange(lvgs.ToArray());
        _listview.EndUpdate();
    }

    #region overridden methods

    public override bool Equals(object obj)
    {
        return _listview.Equals(obj);
    }

    public override int GetHashCode()
    {
        return _listview.GetHashCode();
    }

    public override string ToString()
    {
        return _listview.ToString();
    }

    #endregion
}

历史

  • 2009 年 8 月 17 日 - 发布第一个版本。
© . All rights reserved.