ListBox.ObjectCollection Class

Definition

表示 ListBox 中项的集合。Represents the collection of items in a ListBox.

public: ref class ListBox::ObjectCollection : System::Collections::IList
[System.ComponentModel.ListBindable(false)]
public class ListBox.ObjectCollection : System.Collections.IList
type ListBox.ObjectCollection = class
    interface IList
    interface ICollection
    interface IEnumerable
Public Class ListBox.ObjectCollection
Implements IList
Inheritance
ListBox.ObjectCollection
Derived
Attributes
Implements

Examples

下面的代码示例演示了一个所有者描述的 ListBox,方法是将 DrawMode 属性设置为 OwnerDrawVariable 值并处理 DrawItemMeasureItem 事件。The following code example demonstrates an owner-drawn ListBox by setting the DrawMode property to the OwnerDrawVariable value and handling the DrawItem and MeasureItem events. 它还演示如何设置 BorderStyleScrollAlwaysVisible 属性以及如何使用 AddRange 方法。It also demonstrates setting the BorderStyle and ScrollAlwaysVisible properties and using the AddRange method.

若要运行此示例,请将其粘贴到将 System.Drawing 命名空间和 System.Windows.Forms 命名空间导入的空窗体中。To run this example, paste it into an empty form that imports the System.Drawing namespace and the System.Windows.Forms namespace. 从窗体的构造函数或 Load 方法调用 InitializeOwnerDrawnListBoxCall InitializeOwnerDrawnListBox from the form's constructor or Load method.

internal:
   System::Windows::Forms::ListBox^ ListBox1;

private:
   void InitializeOwnerDrawnListBox()
   {
      this->ListBox1 = gcnew System::Windows::Forms::ListBox;
      
      // Set the location and size.
      ListBox1->Location = Point(20,20);
      ListBox1->Size = System::Drawing::Size( 240, 240 );
      
      // Populate the ListBox.ObjectCollection property 
      // with several strings, using the AddRange method.
      array<Object^>^temp0 = {"System.Windows.Forms","System.Drawing","System.Xml","System.Net","System.Runtime.Remoting","System.Web"};
      this->ListBox1->Items->AddRange( temp0 );
      
      // Turn off the scrollbar.
      ListBox1->ScrollAlwaysVisible = false;
      
      // Set the border style to a single, flat border.
      ListBox1->BorderStyle = BorderStyle::FixedSingle;
      
      // Set the DrawMode property to the OwnerDrawVariable value. 
      // This means the MeasureItem and DrawItem events must be 
      // handled.
      ListBox1->DrawMode = DrawMode::OwnerDrawVariable;
      ListBox1->MeasureItem += gcnew MeasureItemEventHandler( this, &Form1::ListBox1_MeasureItem );
      ListBox1->DrawItem += gcnew DrawItemEventHandler( this, &Form1::ListBox1_DrawItem );
      this->Controls->Add( this->ListBox1 );
   }

   // Handle the DrawItem event for an owner-drawn ListBox.
   void ListBox1_DrawItem( Object^ /*sender*/, DrawItemEventArgs^ e )
   {
      // If the item is the selected item, then draw the rectangle
      // filled in blue. The item is selected when a bitwise And  
      // of the State property and the DrawItemState.Selected 
      // property is true.
      if ( (e->State & DrawItemState::Selected) == DrawItemState::Selected )
      {
         e->Graphics->FillRectangle( Brushes::CornflowerBlue, e->Bounds );
      }
      else
      {
         
         // Otherwise, draw the rectangle filled in beige.
         e->Graphics->FillRectangle( Brushes::Beige, e->Bounds );
      }
      
      // Draw a rectangle in blue around each item.
      e->Graphics->DrawRectangle( Pens::Blue, e->Bounds );
      
      // Draw the text in the item.
      e->Graphics->DrawString( ListBox1->Items[ e->Index ]->ToString(), this->Font, Brushes::Black, (float)e->Bounds.X, (float)e->Bounds.Y );
      
      // Draw the focus rectangle around the selected item.
      e->DrawFocusRectangle();
   }


   // Handle the MeasureItem event for an owner-drawn ListBox.
   void ListBox1_MeasureItem( Object^ sender, MeasureItemEventArgs^ e )
   {
      
      // Cast the sender object back to ListBox type.
      ListBox^ theListBox = dynamic_cast<ListBox^>(sender);
      
      // Get the string contained in each item.
      String^ itemString = dynamic_cast<String^>(theListBox->Items[ e->Index ]);
      
      // Split the string at the " . "  character.
      array<Char>^temp1 = {'.'};
      array<String^>^resultStrings = itemString->Split( temp1 );
      
      // If the string contains more than one period, increase the 
      // height by ten pixels; otherwise, increase the height by 
      // five pixels.
      if ( resultStrings->Length > 2 )
      {
         e->ItemHeight += 10;
      }
      else
      {
         e->ItemHeight += 5;
      }
   }
internal System.Windows.Forms.ListBox ListBox1;

private void InitializeOwnerDrawnListBox()
{
    this.ListBox1 = new System.Windows.Forms.ListBox();

    // Set the location and size.
    ListBox1.Location = new Point(20, 20);
    ListBox1.Size = new Size(240, 240);

    // Populate the ListBox.ObjectCollection property 
    // with several strings, using the AddRange method.
    this.ListBox1.Items.AddRange(new object[]{"System.Windows.Forms", 
        "System.Drawing", "System.Xml", "System.Net", "System.Runtime.Remoting", 
        "System.Web"});

    // Turn off the scrollbar.
    ListBox1.ScrollAlwaysVisible = false;

    // Set the border style to a single, flat border.
    ListBox1.BorderStyle = BorderStyle.FixedSingle;

    // Set the DrawMode property to the OwnerDrawVariable value. 
    // This means the MeasureItem and DrawItem events must be 
    // handled.
    ListBox1.DrawMode = DrawMode.OwnerDrawVariable;
    ListBox1.MeasureItem += 
        new MeasureItemEventHandler(ListBox1_MeasureItem);
    ListBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
    this.Controls.Add(this.ListBox1);
}

// Handle the DrawItem event for an owner-drawn ListBox.
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{

    // If the item is the selected item, then draw the rectangle
    // filled in blue. The item is selected when a bitwise And  
    // of the State property and the DrawItemState.Selected 
    // property is true.
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
    {
        e.Graphics.FillRectangle(Brushes.CornflowerBlue, e.Bounds);
    }
    else
    {
        // Otherwise, draw the rectangle filled in beige.
        e.Graphics.FillRectangle(Brushes.Beige, e.Bounds);
    }

    // Draw a rectangle in blue around each item.
    e.Graphics.DrawRectangle(Pens.Blue, e.Bounds);

    // Draw the text in the item.
    e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(),
        this.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y);

    // Draw the focus rectangle around the selected item.
    e.DrawFocusRectangle();
}

// Handle the MeasureItem event for an owner-drawn ListBox.
private void ListBox1_MeasureItem(object sender, 
    MeasureItemEventArgs e)
{

    // Cast the sender object back to ListBox type.
    ListBox theListBox = (ListBox) sender;

    // Get the string contained in each item.
    string itemString = (string) theListBox.Items[e.Index];

    // Split the string at the " . "  character.
    string[] resultStrings = itemString.Split('.');

    // If the string contains more than one period, increase the 
    // height by ten pixels; otherwise, increase the height by 
    // five pixels.
    if (resultStrings.Length>2)
    {
        e.ItemHeight += 10;
    }
    else
    {
        e.ItemHeight += 5;
    }
}

Friend WithEvents ListBox1 As System.Windows.Forms.ListBox

Private Sub InitializeOwnerDrawnListBox()
    Me.ListBox1 = New System.Windows.Forms.ListBox

    ' Set the location and size.
    ListBox1.Location = New Point(20, 20)
    ListBox1.Size = New Size(240, 240)

    ' Populate the ListBox.ObjectCollection property 
    ' with several strings, using the AddRange method.
    Me.ListBox1.Items.AddRange(New Object() _
        {"System.Windows.Forms", "System.Drawing", "System.Xml", _
        "System.Net", "System.Runtime.Remoting", "System.Web"})

    ' Turn off the scrollbar.
    ListBox1.ScrollAlwaysVisible = False

    ' Set the border style to a single, flat border.
    ListBox1.BorderStyle = BorderStyle.FixedSingle

    ' Set the DrawMode property to the OwnerDrawVariable value. 
    ' This means the MeasureItem and DrawItem events must be 
    ' handled.
    ListBox1.DrawMode = DrawMode.OwnerDrawVariable
    Me.Controls.Add(Me.ListBox1)
End Sub


' Handle the DrawItem event for an owner-drawn ListBox.
Private Sub ListBox1_DrawItem(ByVal sender As Object, _
    ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem

    ' If the item is the selected item, then draw the rectangle filled in
    ' blue. The item is selected when a bitwise And of the State property
    ' and the DrawItemState.Selected property is true. 
    If (e.State And DrawItemState.Selected = DrawItemState.Selected) Then
        e.Graphics.FillRectangle(Brushes.CornflowerBlue, e.Bounds)
    Else
        ' Otherwise, draw the rectangle filled in beige.
        e.Graphics.FillRectangle(Brushes.Beige, e.Bounds)
    End If

    ' Draw a rectangle in blue around each item.
    e.Graphics.DrawRectangle(Pens.Blue, e.Bounds)

    ' Draw the text in the item.
    e.Graphics.DrawString(Me.ListBox1.Items(e.Index), Me.Font, _
        Brushes.Black, e.Bounds.X, e.Bounds.Y)

    ' Draw the focus rectangle around the selected item.
    e.DrawFocusRectangle()
End Sub

' Handle the MeasureItem event for an owner-drawn ListBox.
Private Sub ListBox1_MeasureItem(ByVal sender As Object, _
    ByVal e As MeasureItemEventArgs) Handles ListBox1.MeasureItem

    ' Cast the sender object back to ListBox type.
    Dim theListBox As ListBox = CType(sender, ListBox)

    ' Get the string contained in each item.
    Dim itemString As String = CType(theListBox.Items(e.Index), String)

    ' Split the string at the " . "  character.
    Dim resultStrings() As String = itemString.Split(".")

    ' If the string contains more than one period, increase the 
    ' height by ten pixels; otherwise, increase the height by 
    ' five pixels.
    If (resultStrings.Length > 2) Then
        e.ItemHeight += 10
    Else
        e.ItemHeight += 5
    End If

End Sub

Remarks

ListBox.ObjectCollection 类存储 ListBox中显示的项。The ListBox.ObjectCollection class stores the items displayed in the ListBox. ListBox 类中定义了另外两个集合,使你能够确定在此集合中选择了哪些项。There are two other collections defined within the ListBox class that enable you to determine what items are selected within this collection. ListBox.SelectedObjectCollection 类提供的属性和方法用于确定在 ListBox.ObjectCollection中选择了哪些项,而 ListBox.SelectedIndexCollection 类可用于确定所选 ListBox.ObjectCollection 中的哪些索引。The ListBox.SelectedObjectCollection class provides properties and methods for determining what items are selected within the ListBox.ObjectCollection, while the ListBox.SelectedIndexCollection class enables you to determine what indexes within the ListBox.ObjectCollection are selected.

可以通过多种方法向集合中添加项。There are a number of ways to add items to the collection. Add 方法提供向集合添加单个对象的功能。The Add method provides the ability to add a single object to the collection. 若要将多个对象添加到集合中,请创建一个项的数组,并将其分配给 AddRange 方法。To add a number of objects to the collection, you create an array of items and assign it to the AddRange method. 如果要在集合中的特定位置插入一个对象,则可以使用 Insert 方法。If you want to insert an object at a specific location within the collection, you can use the Insert method. 若要删除项,可以使用 Remove 方法或 RemoveAt 方法(如果你知道项在集合中的位置)。To remove items, you can use either the Remove method or the RemoveAt method if you know where the item is located within the collection. 使用 Clear 方法,您可以从集合中移除所有项,而不是使用 Remove 方法一次删除一个项。The Clear method enables you to remove all items from the collection instead of using the Remove method to remove a single item at a time.

你还可以使用 DataSource 属性来操作 ListBox 的项。You can also manipulate the items of a ListBox by using the DataSource property. 如果使用 DataSource 属性将项添加到 ListBox中,则可以使用 Items 属性查看 ListBox 中的项,但不能使用 ListBox.ObjectCollection的方法在列表中添加或移除项。If you use the DataSource property to add items to a ListBox, you can view the items in the ListBox using the Items property but you cannot add or remove items from the list using the methods of the ListBox.ObjectCollection.

除了用于添加和删除项的方法和属性外,ListBox.ObjectCollection 还提供用于在集合中查找项的方法。In addition to methods and properties for adding and removing items, the ListBox.ObjectCollection also provides methods to find items within the collection. 利用 Contains 方法,您可以确定对象是否为集合的成员。The Contains method enables you to determine whether an object is a member of the collection. 一旦您知道该项位于集合中,就可以使用 IndexOf 方法来确定项在集合中的位置。Once you know that the item is located within the collection, you can use the IndexOf method to determine where the item is located within the collection.

Constructors

ListBox.ObjectCollection(ListBox)

初始化 ListBox.ObjectCollection 的新实例。Initializes a new instance of ListBox.ObjectCollection.

ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection)

初始化基于另一个 ListBox.ObjectCollectionListBox.ObjectCollection 新实例。Initializes a new instance of ListBox.ObjectCollection based on another ListBox.ObjectCollection.

ListBox.ObjectCollection(ListBox, Object[])

初始化包含对象数组的 ListBox.ObjectCollection 新实例。Initializes a new instance of ListBox.ObjectCollection containing an array of objects.

Properties

Count

获取集合中的项数。Gets the number of items in the collection.

IsReadOnly

获取一个值,该值指示集合是否是只读的。Gets a value indicating whether the collection is read-only.

Item[Int32]

获取或设置集合中指定索引处的项。Gets or sets the item at the specified index within the collection.

Methods

Add(Object)

ListBox 的项列表添加项。Adds an item to the list of items for a ListBox.

AddRange(ListBox+ObjectCollection)

将现有 ListBox.ObjectCollection 的项添加到 ListBox 中项的列表中。Adds the items of an existing ListBox.ObjectCollection to the list of items in a ListBox.

AddRange(Object[])

ListBox 的项列表添加项的数组。Adds an array of items to the list of items for a ListBox.

Clear()

从集合中删除所有项。Removes all items from the collection.

Contains(Object)

确定指定的项是否位于集合内。Determines whether the specified item is located within the collection.

CopyTo(Object[], Int32)

将整个集合复制到现有对象的数组中,从该数组内的指定位置开始复制。Copies the entire collection into an existing array of objects at a specified location within the array.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

返回一个枚举数,将使用该枚举数循环访问项集合。Returns an enumerator to use to iterate through the item collection.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
IndexOf(Object)

返回指定的项在集合中的索引。Returns the index within the collection of the specified item.

Insert(Int32, Object)

将一个项插入列表框中指定的索引处。Inserts an item into the list box at the specified index.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(Object)

从集合中删除指定的对象。Removes the specified object from the collection.

RemoveAt(Int32)

删除集合中指定索引处的项。Removes the item at the specified index within the collection.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

ICollection.CopyTo(Array, Int32)

将集合的元素复制到数组,从特定数组索引处开始复制。Copies the elements of the collection to an array, starting at a particular array index.

ICollection.IsSynchronized

有关此成员的说明,请参见 IsSynchronizedFor a description of this member, see IsSynchronized.

ICollection.SyncRoot

有关此成员的说明,请参见 SyncRootFor a description of this member, see SyncRoot.

IList.Add(Object)

将对象添加到 ListBox 类中。Adds an object to the ListBox class.

IList.IsFixedSize

有关此成员的说明,请参见 IsFixedSizeFor a description of this member, see IsFixedSize.

Extension Methods

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

Applies to

See also