我在WinForms中无法弄清如何向ListBox
添加项目。
我尝试了:
list.DisplayMember = "clan";
list.ValueMember = sifOsoba;
如何将一个以int
值为基础的列表与一些文本作为DisplayMember
,添加ValueMember
?
list.Items.add(?)
顺便说一句,由于某些原因我无法使用ListBoxItem
。
我在WinForms中无法弄清如何向ListBox
添加项目。
我尝试了:
list.DisplayMember = "clan";
list.ValueMember = sifOsoba;
如何将一个以int
值为基础的列表与一些文本作为DisplayMember
,添加ValueMember
?
list.Items.add(?)
顺便说一句,由于某些原因我无法使用ListBoxItem
。
ListBoxItem 是 WPF 中的类,而不是 WinForms 类。
在 WPF 中,请使用 ListBoxItem。
在 WinForms 中,该项是 Object 类型,因此请使用以下方法之一:
1. 为 Object 类型提供自己的 ToString() 方法。
2. 使用 DisplayMember 和 ValueMember 进行数据绑定 (请参见 Kelsey 的答案)。
Assembly: PresentationFramework (in PresentationFramework.dll)
,这意味着该类在WPF中定义。一个普通的WinForms应用程序甚至不会引用到WPF dll。 - AZ.list.Items.add(new ListBoxItem("name", "value"));
ListBox的内部(默认)数据结构是ListBoxItem。
ValueMember
和 DisplayMember
属性。如果您不需要数据绑定,则可以将任意对象添加为 ListItem
。ToString()
方法。因此,强烈建议仅向 ListBox 添加可以产生有意义输出的对象。您可能想查看这个SO问题:
DisplayMember和ValueMember主要在您绑定带有这些属性定义的对象时才有用。然后,您需要添加该对象的实例。
例如:
public class MyObject
{
public string clan { get; set; }
public int sifOsoba { get; set; }
public MyObject(string aClan, int aSif0soba)
{
this.clan = aClan;
this.sif0soba = aSif0soba;
}
public override string ToString() { return this.clan; }
}
....
list.Items.Add(new MyObject("hello", 5));
ListBox.Items.Add("some text");
MyClass c = new MyClass();
listBox1.Items.Add(c);
private void listBox1_Format(object sender, ListControlConvertEventArgs e)
{
if(e.ListItem is MyClass)
{
e.Value = ((MyClass)e.ListItem).ToString();
}
else
{
e.Value = "Unknown item added";
}
}
e.Value代表显示文本
然后您可以尝试将SelectedItem强制转换为MyClass,以便访问其中的任何内容。
另外请注意,您可以在Items集合中使用任何继承自对象的内容(几乎包括所有内容)。
for (int x = 1; x <= 50; x++)
{
list.Items.Add(x);
}
除非您添加具有特定属性的对象以供用户显示,否则无需设置DisplayMember和ValueMember。在您的示例中:
listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });
list.Items.add( new ListBoxItem("clan", "sifOsoba"));