ListBox.ObjectCollection ListBox.ObjectCollection ListBox.ObjectCollection ListBox.ObjectCollection Class

定义

表示 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
继承
ListBox.ObjectCollectionListBox.ObjectCollectionListBox.ObjectCollectionListBox.ObjectCollection
派生
属性
实现

示例

下面的代码示例演示了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. InitializeOwnerDrawnListBox窗体的构造函数或Load方法调用。Call 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

注解

类存储中显示的项。 ListBox ListBox.ObjectCollectionThe 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.ObjectCollection项的属性和方法,而ListBox.SelectedIndexCollection类可用于确定所选的中的ListBox.ObjectCollection索引。 ListBox.SelectedObjectCollectionThe 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. 方法使你可以从集合中移除所有项,而不是Remove使用方法一次删除一个项。 ClearThe 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使用属性操作的项ListBoxYou 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.

构造函数

ListBox.ObjectCollection(ListBox) ListBox.ObjectCollection(ListBox) ListBox.ObjectCollection(ListBox) ListBox.ObjectCollection(ListBox)

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

ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection) ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection) ListBox.ObjectCollection(ListBox, 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(ListBox, Object[]) ListBox.ObjectCollection(ListBox, Object[]) ListBox.ObjectCollection(ListBox, Object[])

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

属性

Count Count Count Count

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

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

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

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

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

方法

Add(Object) Add(Object) Add(Object) Add(Object)

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

AddRange(ListBox+ObjectCollection) AddRange(ListBox+ObjectCollection) AddRange(ListBox+ObjectCollection) AddRange(ListBox+ObjectCollection)

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

AddRange(Object[]) AddRange(Object[]) AddRange(Object[]) AddRange(Object[])

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

Clear() Clear() Clear() Clear()

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

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

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

CopyTo(Object[], Int32) CopyTo(Object[], Int32) CopyTo(Object[], Int32) CopyTo(Object[], Int32)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
IndexOf(Object) IndexOf(Object) IndexOf(Object) IndexOf(Object)

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

Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object)

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

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
Remove(Object) Remove(Object) Remove(Object) Remove(Object)

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

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

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

ToString() ToString() ToString() ToString()

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

(Inherited from Object)

显式界面实现

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

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

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

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

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

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

IList.Add(Object) IList.Add(Object) IList.Add(Object) IList.Add(Object)

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

IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize

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

扩展方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

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

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

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

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

另请参阅