Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
1 de 1 pessoas classificaram isso como útil - Avalie este tópico

Classe ListViewGroupCollection

Representa a coleção de grupos dentro de um ListView controle.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)
[ListBindableAttribute(false)]
public class ListViewGroupCollection : IList, 
	ICollection, IEnumerable

Use o ListView.Groups propriedade para obter o ListViewGroupCollection associado com um ListView controle. Essa coleção contém o ListViewGroup objetos que representam os grupos mostrados no controle quando o ListView.View propriedade estiver definida como um valor diferente de View.List. Todos os itens que não estejam atribuídos a um agrupar aparecerá no agrupar padrão, que tem o rótulo do cabeçalho "DefaultGroup {0}". O agrupar padrão não está contido no ListView.Groups coleção e não pode ser alterado. É principalmente útil para depuração para garantir que todos os itens foram adicionados corretamente a grupos. Se não houver nenhum grupos no ListView.Groups coleção, o recurso de agrupamento está desabilitado.

Use o Add método para adicionar um único agrupar à coleção. Use o Insert método para adicionar um agrupar em um índice específico dentro da coleção. Para remover um agrupar, use o Remove método. Use o RemoveAt método para remover o agrupar em um índice específico.

Não é possível adicionar um ListViewGroup a coleção mais de uma vez. Para reposicionar um agrupar dentro da coleção, primeiro ele deve ser removido da coleção e, em seguida, inserido no local desejado. Use o Contains método para determinar se um determinado agrupar já está na coleção. Para recuperar o índice de um agrupar dentro da coleção, use o IndexOf método. Você pode obter ou conjunto o agrupar em um índice específico com o Item indexador.

Use o AddRange método para adicionar vários grupos à coleção. Você pode adicionar vários grupos sistema autônomo uma matriz de grupos ou sistema autônomo um ListViewGroupCollection recuperados por meio do ListView.Groups propriedade de outro ListView controle. Use o Clear método para remover todos os grupos da coleção.

Observação Observação:

O Remove, RemoveAt, e Clear métodos remover grupos da coleção, mas não remova nenhum item das ListView controle. Se não houver nenhum grupos no ListView.Groups coleção, o recurso de agrupamento está desabilitado e todos os itens no controle são exibidos normalmente.

The AddRange e Clear métodos são úteis quando você deseja fornecer várias maneiras de agrupar itens em um ListView controle. Para fazer isso, crie vários arrays de agrupar. Para alterar o agrupamento, primeiro use o Clear método para remover todos os grupos da coleção, use o AddRange método para adicionar a seguinte matriz de exibir os grupos.

Use o CopyTo método para copiar os grupos em uma coleção para um array compatível começando em um índice especificado. Isso é útil, por exemplo, quando você deseja classificar os grupos na coleção usando o Array.Sort método. Para fazer isso, copie os grupos em um array compatível e, em seguida, classificar a matriz. Em seguida, use o Clear método para remover todos os grupos da coleção, use o AddRange Para adicionar a matriz classificada de volta para a coleção.

Use o Count propriedade para determinar quantos grupos estiverem na coleção. Para iterar na coleção, use o IEnumerator retornado pela GetEnumerator método.

Observação Observação:

O recurso de agrupamento está disponível somente no Windows XP e a família Windows servidor 2003 quando o aplicativo chama o Application.EnableVisualStyles método. Em sistemas operacionais anteriores, qualquer código relacionadas a grupos será ignorado e os grupos não aparecerá. sistema autônomo resultado, qualquer código que depende o recurso de agrupamento pode não funcionar corretamente. Você pode desejar incluir um teste determina se o recurso de agrupamento está disponível e fornecer funcionalidade alternativa quando não estiver disponível. Por exemplo, convém fornecer classificação alternativo quando executado em sistemas operacionais que não oferecem suporte a classificação por agrupar.

O recurso de marca de inserção é fornecido pela mesma biblioteca que fornece o recurso de temas do sistema operacional. Para verificar a disponibilidade desta biblioteca telefonar o FeatureSupport.IsPresent(Object) método de sobrecarga e passar a OSFeature.Themes valor.

O exemplo a seguir demonstra como usar o ListView Agrupar recursos para organizar itens pelo valor subitem no modo de exibição detalhes. Essa forma de agrupamento é semelhante ao agrupamento usado no Windows Explorer. No exemplo, os grupos são criados dinamicamente. Para cada coluna de subitem, um agrupar é criado para cada valor subitem exclusivo. Para a coluna do item pai, um agrupar é criado para cada letra inicial exclusiva. Clique no cabeçalho de uma coluna classifica os itens para os grupos criados para essa coluna. Clicando no cabeçalho da mesma coluna novamente inverte a ordem dos grupos.

using System;
using System.Collections; 
using System.Windows.Forms;

publicclass ListViewGroupsExample : Form
{
    private ListView myListView;

    // Determine whether Windows XP or a later// operating system is present.privatebool 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]
    staticvoid Main() 
    {
        Application.EnableVisualStyles();
        Application.Run(new ListViewGroupsExample());
    }

    // Groups the items using the groups created for the clicked // column.privatevoid 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.privatevoid 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.privateclass 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.publicint Compare(object x, object y)
        {
            int result = String.Compare(
                ((ListViewGroup)x).Header,
                ((ListViewGroup)y).Header
            );
            if (order == SortOrder.Ascending)
            {
                return result;
            }
            else 
            {
                return -result;
            }
        }
    }

}


import System.*;
import System.Collections.*;
import System.Windows.Forms.*;

public class ListViewGroupsExample extends Form
{
    private ListView myListView;
    private boolean isRunningXPOrLater = false;

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

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

    public ListViewGroupsExample()
    {
        // Initialize myListView.
        myListView = new ListView();
        myListView.set_Dock(DockStyle.Fill);
        myListView.set_View(View.Details);
        myListView.set_Sorting(SortOrder.Ascending);
        // Create and initialize column headers for myListView.
        ColumnHeader columnHeader0 = new ColumnHeader();
        columnHeader0.set_Text("Title");
        columnHeader0.set_Width(-1);
        ColumnHeader columnHeader1 = new ColumnHeader();
        columnHeader1.set_Text("Author");
        columnHeader1.set_Width(-1);
        ColumnHeader columnHeader2 = new ColumnHeader();
        columnHeader2.set_Text("Year");
        columnHeader2.set_Width(-1);
        // Add the column headers to myListView.
        myListView.get_Columns().AddRange(new ColumnHeader[] { 
            columnHeader0, columnHeader1, columnHeader2 });
        // Add a handler for the ColumnClick event.
        myListView.add_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.get_Items().AddRange(new ListViewItem[] { 
            item0, item1, item2, item3, item4, item5 });
        // Determine whether Windows XP or a later 
        // operating system is present.
        if (System.Environment.get_OSVersion().get_Version().get_Major() > 5 
            || (System.Environment.get_OSVersion().get_Version().get_Major() 
            == 5 && System.Environment.get_OSVersion().get_Version().get_Minor() 
            >= 1)) {
            isRunningXPOrLater = true;
        }

        if (isRunningXPOrLater) {
            // Create the groupsTable array and populate it with one 
            // hash table for each column.
            groupTables = new Hashtable[myListView.get_Columns().get_Count()];
            for (int column = 0; column < myListView.get_Columns().get_Count(); 
                column++) {
                // Create a hash table containing all the groups 
                // needed for a single column.
                groupTables.set_Item(column, CreateGroupsTable(column));
            }
            // Start with the groups created for the Title column.
            SetGroups(0);
        }
        // Initialize the form.
        this.get_Controls().Add(myListView);
        this.set_Size(new System.Drawing.Size(550, 330));
        this.set_Text("ListView Groups Example");
    } //ListViewGroupsExample

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new ListViewGroupsExample());
    } //main

    // 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.get_Sorting().Equals(SortOrder.Descending) 
            || (isRunningXPOrLater && e.get_Column() != groupColumn)) {
            myListView.set_Sorting(SortOrder.Ascending);
        }
        else {
            myListView.set_Sorting(SortOrder.Descending);
        }
        groupColumn = e.get_Column();
        // Set the groups to those created for the clicked column.
        if (isRunningXPOrLater)
        {
            SetGroups(e.get_Column());
        }
    } //myListView_ColumnClick

    // Sets myListView to the groups created for the specified column.
    private void SetGroups(int column)
    {
        // Remove the current groups.
        myListView.get_Groups().Clear();
        // Retrieve the hash table corresponding to the column.
        Hashtable groups = (Hashtable)groupTables.get_Item(column);
        // Iterate through the items in myListView, assigning each 
        // one to the appropriate group.
        for (int iCtr = 0; iCtr < myListView.get_Items().get_Count(); iCtr++) {
            ListViewItem item = myListView.get_Items().get_Item(iCtr);
            // Retrieve the subitem text corresponding to the column.
            String subItemText = item.get_SubItems().get_Item(column).get_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.set_Group((ListViewGroup)(groups.get_Item(subItemText)));
        }
        // Copy the groups for the column to an array.
        ListViewGroup groupsArray[] = new ListViewGroup[groups.get_Count()];
        groups.get_Values().CopyTo(groupsArray, 0);
        // Sort the groups and add them to myListView.
        Array.Sort(groupsArray, new ListViewGroupSorter(
            myListView.get_Sorting()));
        myListView.get_Groups().AddRange(groupsArray);
    } //SetGroups

    // 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.
        for (int iCtr = 0; iCtr < myListView.get_Items().get_Count(); iCtr++) {
            ListViewItem item = myListView.get_Items().get_Item(iCtr);
            // Retrieve the text value for the column.
            String subItemText = item.get_SubItems().get_Item(column).get_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;
    } //CreateGroupsTable

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

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

        // 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).get_Header(), 
                ((ListViewGroup)y).get_Header());
            if (order.Equals(SortOrder.Ascending)) {
                return result;
            }
            else {
                return -result;
            }
        } //Compare
    } //ListViewGroupSorter
} //ListViewGroupsExample 


System.Object
  System.Windows.Forms.ListViewGroupCollection
Quaisquer membros static (Shared no Visual Basic) públicos deste tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.

.NET Framework

Compatível com: 3.5, 3.0, 2.0
Isso foi útil para você?
(1500 caracteres restantes)
Conteúdo da Comunidade Adicionar