ColumnHeader Класс

Определение

Отображает заголовок одного столбца в элементе управления ListView.

public ref class ColumnHeader : System::ComponentModel::Component, ICloneable
public class ColumnHeader : System.ComponentModel.Component, ICloneable
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ColumnHeaderConverter))]
public class ColumnHeader : System.ComponentModel.Component, ICloneable
type ColumnHeader = class
    inherit Component
    interface ICloneable
[<System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ColumnHeaderConverter))>]
type ColumnHeader = class
    inherit Component
    interface ICloneable
Public Class ColumnHeader
Inherits Component
Implements ICloneable
Наследование
Атрибуты
Реализации

Примеры

В следующем примере кода демонстрируется инициализация ListView элемента управления . В примере создаются ColumnHeader объекты и задаются свойства заголовка столбца Text, TextAlign и Width . В примере также добавляются элементы и подэлементы в ListView. Чтобы запустить этот пример, вставьте следующий код в форму и вызовите PopulateListView метод из конструктора или Load обработчика событий формы.

private:
   void PopulateListView()
   {
      ListView1->Width = 270;
      ListView1->Location = System::Drawing::Point( 10, 10 );
      
      // Declare and construct the ColumnHeader objects.
      ColumnHeader^ header1;
      ColumnHeader^ header2;
      header1 = gcnew ColumnHeader;
      header2 = gcnew ColumnHeader;
      
      // Set the text, alignment and width for each column header.
      header1->Text = "File name";
      header1->TextAlign = HorizontalAlignment::Left;
      header1->Width = 70;
      header2->TextAlign = HorizontalAlignment::Left;
      header2->Text = "Location";
      header2->Width = 200;
      
      // Add the headers to the ListView control.
      ListView1->Columns->Add( header1 );
      ListView1->Columns->Add( header2 );
            
      // Specify that each item appears on a separate line.
      ListView1->View = View::Details;

      // Populate the ListView.Items property.
      // Set the directory to the sample picture directory.
      System::IO::DirectoryInfo^ dirInfo = gcnew System::IO::DirectoryInfo( "C:\\Documents and Settings\\All Users"
      "\\Documents\\My Pictures\\Sample Pictures" );
      
      // Get the .jpg files from the directory
      array<System::IO::FileInfo^>^files = dirInfo->GetFiles( "*.jpg" );
      
      // Add each file name and full name including path
      // to the ListView.
      if ( files != nullptr )
      {
         System::Collections::IEnumerator^ myEnum = files->GetEnumerator();
         while ( myEnum->MoveNext() )
         {
            System::IO::FileInfo^ file = safe_cast<System::IO::FileInfo^>(myEnum->Current);
            ListViewItem^ item = gcnew ListViewItem( file->Name );
            item->SubItems->Add( file->FullName );
            ListView1->Items->Add( item );
         }
      }
   }
private void PopulateListView()
{
    ListView1.Width = 270;
    ListView1.Location = new System.Drawing.Point(10, 10);

    // Declare and construct the ColumnHeader objects.
    ColumnHeader header1, header2;
    header1 = new ColumnHeader();
    header2 = new ColumnHeader();

    // Set the text, alignment and width for each column header.
    header1.Text = "File name";
    header1.TextAlign = HorizontalAlignment.Left;
    header1.Width = 70;

    header2.TextAlign = HorizontalAlignment.Left;
    header2.Text = "Location";
    header2.Width = 200;

    // Add the headers to the ListView control.
    ListView1.Columns.Add(header1);
    ListView1.Columns.Add(header2);

    // Specify that each item appears on a separate line.
    ListView1.View = View.Details;
    
    // Populate the ListView.Items property.
    // Set the directory to the sample picture directory.
    System.IO.DirectoryInfo dirInfo = 
        new System.IO.DirectoryInfo(
        "C:\\Documents and Settings\\All Users" +
        "\\Documents\\My Pictures\\Sample Pictures");

    // Get the .jpg files from the directory
    System.IO.FileInfo[] files = dirInfo.GetFiles("*.jpg");

    // Add each file name and full name including path
    // to the ListView.
    if (files != null)
    {
        foreach ( System.IO.FileInfo file in files )
        {
            ListViewItem item = new ListViewItem(file.Name);
            item.SubItems.Add(file.FullName);
            ListView1.Items.Add(item);
        }
    }
}
Private Sub PopulateListView()
    ListView1.Width = 270
    ListView1.Location = New System.Drawing.Point(10, 10)

    ' Declare and construct the ColumnHeader objects.
    Dim header1, header2 As ColumnHeader
    header1 = New ColumnHeader
    header2 = New ColumnHeader

    ' Set the text, alignment and width for each column header.
    header1.Text = "File name"
    header1.TextAlign = HorizontalAlignment.Left
    header1.Width = 70

    header2.TextAlign = HorizontalAlignment.Left
    header2.Text = "Location"
    header2.Width = 200

    ' Add the headers to the ListView control.
    ListView1.Columns.Add(header1)
    ListView1.Columns.Add(header2)

    ' Specify that each item appears on a separate line.
    ListView1.View = View.Details

    ' Populate the ListView.Items property.
    ' Set the directory to the sample picture directory.
    Dim dirInfo As New System.IO.DirectoryInfo _
        ("C:\Documents and Settings\All Users" _
        & "\Documents\My Pictures\Sample Pictures")
    Dim file As System.IO.FileInfo

    ' Get the .jpg files from the directory
    Dim files() As System.io.FileInfo = dirInfo.GetFiles("*.jpg")

    ' Add each file name and full name including path
    ' to the ListView.
    If (files IsNot Nothing) Then
        For Each file In files
            Dim item As New ListViewItem(file.Name)
            item.SubItems.Add(file.FullName)
            ListView1.Items.Add(item)
        Next
    End If
End Sub

Комментарии

Заголовок столбца — это элемент в элементе ListView управления, содержащий текст заголовка. ColumnHeader Объекты можно добавить в с ListView помощью Add метода ListView.ColumnHeaderCollection класса . Чтобы добавить группу столбцов в ListView, можно использовать AddRange метод ListView.ColumnHeaderCollection класса . Можно использовать Index свойство класса , ColumnHeader чтобы определить, где ColumnHeader находится в ListView.ColumnHeaderCollection.

ColumnHeaderText предоставляет свойства и TextAlign для задания текста, отображаемого в элементе управления, и выравнивания текста в заголовке столбца. Чтобы определить, связан ли ColumnHeader объект с элементом ListView управления, можно сослаться на ListView свойство . Если вы хотите скопировать ColumnHeader для использования в другом ListView элементе Clone управления, можно использовать метод .

Конструкторы

ColumnHeader()

Инициализирует новый экземпляр класса ColumnHeader.

ColumnHeader(Int32)

Инициализирует новый экземпляр класса ColumnHeader с указанным изображением.

ColumnHeader(String)

Инициализирует новый экземпляр класса ColumnHeader с указанным изображением.

Свойства

CanRaiseEvents

Возвращает значение, показывающее, может ли компонент вызывать событие.

(Унаследовано от Component)
Container

Возвращает объект IContainer, который содержит коллекцию Component.

(Унаследовано от Component)
DesignMode

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время.

(Унаследовано от Component)
DisplayIndex

Возвращает или задает расположение столбца относительно столбцов, отображаемых в текущий момент.

Events

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component.

(Унаследовано от Component)
ImageIndex

Получает или задает индекс изображения, отображаемого в ColumnHeader.

ImageKey

Получает или задает ключ изображения, отображаемого в столбце.

ImageList

Получает список изображений, связанный с ColumnHeader.

Index

Получает расположение ListView этого столбца элемента управления ListView.ColumnHeaderCollection.

ListView

Получает элемент управления ListView, в котором расположен ColumnHeader.

Name

Возвращает или задает имя таблицы для объекта ColumnHeader.

Site

Получает или задает ISite объекта Component.

(Унаследовано от Component)
Tag

Получает или задает объект, содержащий данные, связанные с ColumnHeader.

Text

Получает или задает текст, отображаемый в заголовке столбца.

TextAlign

Получает или задает выравнивание по горизонтали текста, отображаемого в заголовке столбца ColumnHeader.

Width

Получает или задает ширину столбца.

Методы

AutoResize(ColumnHeaderAutoResizeStyle)

Изменяет ширину данного столбца в соответствии со стилем изменения размера.

Clone()

Создает идентичную копию текущего заголовка столбца ColumnHeader, не связанную ни с одним элементом управления представления списка.

CreateObjRef(Type)

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом.

(Унаследовано от MarshalByRefObject)
Dispose()

Освобождает все ресурсы, занятые модулем Component.

(Унаследовано от Component)
Dispose(Boolean)

Уничтожает ресурсы (кроме памяти), используемые классом ColumnHeader.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetLifetimeService()
Устаревшие..

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра.

(Унаследовано от MarshalByRefObject)
GetService(Type)

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container.

(Унаследовано от Component)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
InitializeLifetimeService()
Устаревшие..

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject.

(Унаследовано от MarshalByRefObject)
ToString()

Возвращает объект String, содержащий имя Component, если оно есть. Этот метод не следует переопределять.

События

Disposed

Возникает при удалении компонента путем вызова метода Dispose().

(Унаследовано от Component)

Применяется к

См. также раздел