ListView.Groups 属性

定义

获取分配给控件的 ListViewGroup 对象的集合。

C#
public System.Windows.Forms.ListViewGroupCollection Groups { get; }

属性值

一个包含 ListViewGroupCollection 控件中所有的组的 ListView

示例

下面的代码示例演示如何使用 ListView 分组功能按详细信息视图中的子项值组织项。 这种分组形式类似于 Windows 资源管理器中使用的分组。 在此示例中,组是动态创建的。 对于每个子项列,为每个唯一子项值创建一个组。 对于父项列,为每个唯一的首字母创建一个组。 单击列的标题会将项目排序到为该列创建的组中。 再次单击同一列标题会反转组的顺序。

C#
using System;
using System.Collections; 
using System.Windows.Forms;

public class ListViewGroupsExample : Form
{
    private ListView myListView;

    // Determine whether Windows XP or a later
    // operating system is present.
    private bool isRunningXPOrLater = 
        OSFeature.Feature.IsPresent(OSFeature.Themes);

    // Declare a Hashtable array in which to store the groups.
    private Hashtable[] groupTables;

    // Declare a variable to store the current grouping column.
    int groupColumn = 0;

    public ListViewGroupsExample()
    {
        // Initialize myListView.
        myListView = new ListView();
        myListView.Dock = DockStyle.Fill;
        myListView.View = View.Details;
        myListView.Sorting = SortOrder.Ascending;

        // Create and initialize column headers for myListView.
        ColumnHeader columnHeader0 = new ColumnHeader();
        columnHeader0.Text = "Title";
        columnHeader0.Width = -1;
        ColumnHeader columnHeader1 = new ColumnHeader();
        columnHeader1.Text = "Author";
        columnHeader1.Width = -1;
        ColumnHeader columnHeader2 = new ColumnHeader();
        columnHeader2.Text = "Year";
        columnHeader2.Width = -1;

        // Add the column headers to myListView.
        myListView.Columns.AddRange(new ColumnHeader[] 
            {columnHeader0, columnHeader1, columnHeader2});

        // Add a handler for the ColumnClick event.
        myListView.ColumnClick += 
            new ColumnClickEventHandler(myListView_ColumnClick);

        // Create items and add them to myListView.
        ListViewItem item0 = new ListViewItem( new string[] 
            {"Programming Windows", 
            "Petzold, Charles", 
            "1998"} );
        ListViewItem item1 = new ListViewItem( new string[] 
            {"Code: The Hidden Language of Computer Hardware and Software", 
            "Petzold, Charles", 
            "2000"} );
        ListViewItem item2 = new ListViewItem( new string[] 
            {"Programming Windows with C#", 
            "Petzold, Charles", 
            "2001"} );
        ListViewItem item3 = new ListViewItem( new string[] 
            {"Coding Techniques for Microsoft Visual Basic .NET", 
            "Connell, John", 
            "2001"} );
        ListViewItem item4 = new ListViewItem( new string[] 
            {"C# for Java Developers", 
            "Jones, Allen & Freeman, Adam", 
            "2002"} );
        ListViewItem item5 = new ListViewItem( new string[] 
            {"Microsoft .NET XML Web Services Step by Step", 
            "Jones, Allen & Freeman, Adam", 
            "2002"} );
        myListView.Items.AddRange(
            new ListViewItem[] {item0, item1, item2, item3, item4, item5});

        if (isRunningXPOrLater)
        {
            // Create the groupsTable array and populate it with one 
            // hash table for each column.
            groupTables = new Hashtable[myListView.Columns.Count];
            for (int column = 0; column < myListView.Columns.Count; column++)
            {
                // Create a hash table containing all the groups 
                // needed for a single column.
                groupTables[column] = CreateGroupsTable(column);
            }

            // Start with the groups created for the Title column.
            SetGroups(0);
        }

        // Initialize the form.
        this.Controls.Add(myListView);
        this.Size = new System.Drawing.Size(550, 330);
        this.Text = "ListView Groups Example";
    }

    [STAThread]
    static void Main() 
    {
        Application.EnableVisualStyles();
        Application.Run(new ListViewGroupsExample());
    }

    // Groups the items using the groups created for the clicked 
    // column.
    private void myListView_ColumnClick(
        object sender, ColumnClickEventArgs e)
    {
        // Set the sort order to ascending when changing
        // column groups; otherwise, reverse the sort order.
        if ( myListView.Sorting == SortOrder.Descending || 
            ( isRunningXPOrLater && (e.Column != groupColumn) ) )
        {
            myListView.Sorting = SortOrder.Ascending;
        }
        else 
        {
            myListView.Sorting = SortOrder.Descending;
        }
        groupColumn = e.Column;

        // Set the groups to those created for the clicked column.
        if (isRunningXPOrLater)
        {
            SetGroups(e.Column);
        }
    }

    // Sets myListView to the groups created for the specified column.
    private void SetGroups(int column)
    {
        // Remove the current groups.
        myListView.Groups.Clear();

        // Retrieve the hash table corresponding to the column.
        Hashtable groups = (Hashtable)groupTables[column];

        // Copy the groups for the column to an array.
        ListViewGroup[] groupsArray = new ListViewGroup[groups.Count];
        groups.Values.CopyTo(groupsArray, 0);

        // Sort the groups and add them to myListView.
        Array.Sort(groupsArray, new ListViewGroupSorter(myListView.Sorting));
        myListView.Groups.AddRange(groupsArray);

        // Iterate through the items in myListView, assigning each 
        // one to the appropriate group.
        foreach (ListViewItem item in myListView.Items)
        {
            // Retrieve the subitem text corresponding to the column.
            string subItemText = item.SubItems[column].Text;

            // For the Title column, use only the first letter.
            if (column == 0) 
            {
                subItemText = subItemText.Substring(0, 1);
            }

            // Assign the item to the matching group.
            item.Group = (ListViewGroup)groups[subItemText];
        }
    }

    // Creates a Hashtable object with one entry for each unique
    // subitem value (or initial letter for the parent item)
    // in the specified column.
    private Hashtable CreateGroupsTable(int column)
    {
        // Create a Hashtable object.
        Hashtable groups = new Hashtable();

        // Iterate through the items in myListView.
        foreach (ListViewItem item in myListView.Items)
        {
            // Retrieve the text value for the column.
            string subItemText = item.SubItems[column].Text;

            // Use the initial letter instead if it is the first column.
            if (column == 0) 
            {
                subItemText = subItemText.Substring(0, 1);
            }

            // If the groups table does not already contain a group
            // for the subItemText value, add a new group using the 
            // subItemText value for the group header and Hashtable key.
            if (!groups.Contains(subItemText))
            {
                groups.Add( subItemText, new ListViewGroup(subItemText, 
                    HorizontalAlignment.Left) );
            }
        }

        // Return the Hashtable object.
        return groups;
    }

    // Sorts ListViewGroup objects by header value.
    private class ListViewGroupSorter : IComparer
    {
        private SortOrder order;

        // Stores the sort order.
        public ListViewGroupSorter(SortOrder theOrder) 
        { 
            order = theOrder;
        }

        // Compares the groups by header value, using the saved sort
        // order to return the correct value.
        public int Compare(object x, object y)
        {
            int result = String.Compare(
                ((ListViewGroup)x).Header,
                ((ListViewGroup)y).Header
            );
            if (order == SortOrder.Ascending)
            {
                return result;
            }
            else 
            {
                return -result;
            }
        }
    }
}

注解

通过 ListView 分组功能,可以创建逻辑相关 ListView 项的视觉组。 每个组由文本标题后跟水平线和分配给该组的项目组成。 可以将标题文本与控件的左侧、右侧或中心对齐。 当 属性设置为 非 View.List值时,View将显示分配给ListView控件的任何组。

ListView 组通过将项目划分为有用的类别来帮助用户找到他们正在查找的项目。 可以创建所需的任何类别。 一种典型的方法是根据列表的排序方式对项进行分组。 例如,在按字母顺序对列表进行排序时,可以按项目名称的初始字母对项目进行分组,或者单击详细信息视图中的列标题对列表进行排序时按子项(例如类型或日期)对项目进行分组。 Windows 资源管理器使用此类型的分组。

若要使用分组功能,请将一个或多个 ListViewGroup 对象添加到 Groups 控件的 ListView 集合中。 在构造函数中ListViewGroup设置组标头文本和标题对齐方式,或使用 和 ListViewGroup.HeaderAlignment 属性设置它们ListViewGroup.Header

若要暂时禁用分组功能,请将 ShowGroups 属性设置为 false

可以通过在构造函数中 ListViewItem 指定组、设置 ListViewItem.Group 属性或直接将项添加到组的集合来将项分配给 ListViewGroup.Items 组。 所有项都应在显示之前分配给组。 任何未分配给组的项目都将显示在具有标题标签“DefaultGroup{0}”的默认组中。 默认组不包含在集合中 Groups ,并且无法更改。 它主要用于调试,以确保所有项都已正确添加到组。

一个项一次只能位于一个组中。 可以通过在运行时设置 ListViewItem.Group 属性或将其添加到 ListViewGroup.Items 另一个组的集合(这会自动将其从上一组中删除)来更改项所属的组。

使用组时,将禁用插入标记功能。 这是因为分组功能按组成员身份对项进行排序,而插入标记功能用于在尚未对项进行排序的控件中 ListView 拖放重新定位。

ListView 当应用程序调用 Application.EnableVisualStyles 方法时,组仅在 Windows XP 和 Windows Server 2003 上可用。 在较早的操作系统上,与组相关的任何代码都不起作用,并且不会显示组。 因此,依赖于分组功能的任何代码可能无法正常工作。

你可能希望包含用于确定分组功能是否可用的代码,并在功能不可用时提供备用功能。 例如,在不支持按组排序的操作系统上运行时,可能需要提供备用排序。

分组功能由提供操作系统主题功能的同一库提供。 若要检查此库的可用性,请调用 FeatureSupport.IsPresent(Object) 方法重载并传入 OSFeature.Themes 值。

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅