ListViewItem.Group Свойство
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает или задает группу, которой назначается элемент.
public:
property System::Windows::Forms::ListViewGroup ^ Group { System::Windows::Forms::ListViewGroup ^ get(); void set(System::Windows::Forms::ListViewGroup ^ value); };
public System.Windows.Forms.ListViewGroup Group { get; set; }
public System.Windows.Forms.ListViewGroup? Group { get; set; }
member this.Group : System.Windows.Forms.ListViewGroup with get, set
Public Property Group As ListViewGroup
Значение свойства
Объект ListViewGroup , которому назначается элемент.
Примеры
В следующем примере кода показано, как Group свойство можно использовать в приложении, которое упорядочивает ListView элементы по значению подсайтов в представлении сведений. Такая форма группировки аналогична группировке, используемой в проводнике Windows. В примере группы создаются динамически. Для каждого столбца подсети создается одна группа для каждого уникального значения подitem. Для столбца родительского элемента создается одна группа для каждой уникальной исходной буквы. Группы, созданные для каждого столбца, хранятся в хэш-таблице вместе с текстом подсайма или начальной буквой. При щелчке заголовка столбца извлекается хэш-таблица, соответствующая этому столбцу. Затем значения текста подсайма для этого столбца используются в качестве хэш-ключей таблицы для получения правильной группы для каждого элемента. Затем элемент назначается группе с помощью Group свойства.
Этот пример кода является частью более крупного примера, предоставленного для ListView.Groups свойства.
// 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 = dynamic_cast<Hashtable^>(groupTables[column]);
// Copy the groups for the column to an array.
array<ListViewGroup^>^ groupsArray = gcnew array<ListViewGroup^>(groups->Count);
groups->Values->CopyTo(groupsArray, 0);
// Sort the groups and add them to myListView.
Array::Sort(groupsArray, gcnew ListViewGroupSorter(myListView->Sorting));
myListView->Groups->AddRange(groupsArray);
// Iterate through the items in myListView, assigning each
// one to the appropriate group.
IEnumerator^ myEnum = myListView->Items->GetEnumerator();
while (myEnum->MoveNext())
{
ListViewItem^ item = safe_cast<ListViewItem^>(myEnum->Current);
// 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 = dynamic_cast<ListViewGroup^>(groups[subItemText]);
}
}
// 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];
}
}
' Sets myListView to the groups created for the specified column.
Private Sub SetGroups(column As Integer)
' Remove the current groups.
myListView.Groups.Clear()
' Retrieve the hash table corresponding to the column.
Dim groups As Hashtable = CType(groupTables(column), Hashtable)
' Copy the groups for the column to an array.
Dim groupsArray(groups.Count - 1) As ListViewGroup
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.
Dim item As ListViewItem
For Each item In myListView.Items
' Retrieve the subitem text corresponding to the column.
Dim subItemText As String = item.SubItems(column).Text
' For the Title column, use only the first letter.
If column = 0 Then
subItemText = subItemText.Substring(0, 1)
End If
' Assign the item to the matching group.
item.Group = CType(groups(subItemText), ListViewGroup)
Next item
End Sub
Комментарии
Используйте это свойство, чтобы задать группу, к которой принадлежит элемент. Вы также можете задать группу в конструкторе ListViewItem или использовать это свойство для изменения членства в группе во время выполнения. Если это свойство null задано и есть группы в ListView.Groups коллекции, элемент появится в группе по умолчанию, которая имеет метку заголовка DefaultGroupSystem.Windows.Forms. Группа по умолчанию не содержится в ListView.Groups коллекции и не может быть изменена. В первую очередь полезно выполнить отладку, чтобы убедиться, что все элементы были правильно добавлены в группы.
Замечание
ListView Группы доступны только в Windows XP и семействе Windows Server 2003 (Windows XP Home Edition, Windows XP Professional, Windows Server 2003). Дополнительные сведения см. в ListViewGroup разделе обзора.