如何:在 Windows 窗体 ListView 控件中对项进行分组

使用 ListView 控件的分组功能,可以在组中显示相关项集。 这些组在屏幕上由包含组标题的水平组标头分隔。 可以使用 ListView 组,通过按字母顺序、按日期或任何其他逻辑分组来更轻松地导航大型列表。 下图显示了一些分组项。

ListView 奇数组和偶数组的屏幕截图。

若要启用分组,必须先在设计器中或以编程方式创建一个或多个组。 定义组后,可以将 ListView 项分配给组。 还可以以编程方式将项从一个组移动到另一个组。

添加组

  1. 使用 Add 集合的 Groups 方法。

    // Adds a new group that has a left-aligned header
    listView1.Groups.Add(new ListViewGroup("List item text",
        HorizontalAlignment.Left));
    
    ' Adds a new group that has a left-aligned header
    ListView1.Groups.Add(New ListViewGroup("Group 1", _
     HorizontalAlignment.Left))
    

删除组

  1. 使用 Groups 集合的 RemoveAtClear 方法。

    RemoveAt 方法删除单个组;Clear 方法从列表中删除所有组。

    说明

    删除组不会删除该组中的项。

    // Removes the first group in the collection.
    listView1.Groups.RemoveAt(0);
    // Clears all groups.
    listView1.Groups.Clear();
    
    ' Removes the first group in the collection.
    ListView1.Groups.RemoveAt(0)
    ' Clears all groups:
    ListView1.Groups.Clear()
    

向组分配项目或在组之间移动项目

  1. 设置单个项的 ListViewItem.Group 属性。

    // Adds the first item to the first group
    listView1.Items[0].Group = listView1.Groups[0];
    
    ' Adds the first item to the first group
    ListView1.Items.Item(0).Group = ListView1.Groups(0)
    

另请参阅