如何在 foreach 语句的列表框中重复单个项目?
我尝试过 ListBoxItem 但 System.Windows.Controls 在我的 .Net 框架(版本 4)中不被视为有效命名空间。
foreach(ListBoxItem item in listBoxObject.Items)
{
...
}
如何在 foreach 语句的列表框中重复单个项目?
我尝试过 ListBoxItem 但 System.Windows.Controls 在我的 .Net 框架(版本 4)中不被视为有效命名空间。
foreach(ListBoxItem item in listBoxObject.Items)
{
...
}
您会发现这listBoxObject.Items
是一个对象集合,包含您的数据对象而不是控件。
例如,如果我像这样绑定列表框:
listBox1.DataSource = new string[] { "asdf", "qwerty" };
然后该.Items
属性产生一个ObjectCollection
包含两个字符串。
通常,当某人在列表框项目中循环时,他们希望确定它们是否被选中。如果是这种情况,请尝试使用 listBoxObject.SelectedItems 而不是 listBoxObject.Items。这将仅返回已选择的项目。
据我所知,没有 ListBoxItem 对象。您将需要为每个项目使用对象(这是 seletecteditems 和 items 返回的内容)。Object 表示项目的值,因此请相应地使用它(意思是,如果对象是字符串,则将其用作字符串,但如果对象是复杂对象,则照此使用)。
代码示例:
foreach (Object listBoxItem in listBoxObject.SelectedItems)
{
//Use as object or cast to a more specific type of object.
}
而且,如果您知道始终是什么对象,则可以将其转换为 foreach 循环。(警告:如果你错了,这将引发异常)。这个例子是如果只有字符串被输入到列表框中。
foreach (String listBoxItem in listBoxObject.SelectedItems)
{
//Use as String. It has already been cast.
}
foreach(Object item in listBoxObject.Items){ ... }
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.item.aspx
ListBox.Items的类型为System.Windows.Forms.ListBox.ObjectCollection System.Windows.Forms.ListBox.ObjectCollection.Item 的类型为 Object。HTH。