在C#中的ListBox中添加ListBoxItem?

时间:2021-01-16 19:55:35

I know that:

我知道:

String test = "test";
ListBox.Items.Add(test);

or

要么

String test = "test";
int index = 1;
ListBox.Items.Insert(index, String);

adds the String in a ListBox, but I want to insert ListBoxItem, how to? previously I learn that

在ListBox中添加String,但我想插入ListBoxItem,如何?以前我学到了

var contentToString = (String)ListBoxItem.Content;

simply converts ListBoxItem to String, but I couldn't do the opposite to convert String to ListBoxItem

只是将ListBoxItem转换为String,但我无法将String转换为ListBoxItem

3 个解决方案

#1


28  

Try this:

尝试这个:

ListBoxItem itm = new ListBoxItem();
itm.Content = "some text";

listbox.Items.Add(itm);

listbox is name for ListBox.

listbox是ListBox的名称。

#2


1  

You can do like that

你可以这样做

ListBox1.Items.Insert(0,new ListItem("ITEM 1", "Value"))

#3


0  

Your object will always be in a ListBoxItem, the ListBox will generate one for you if you don't add it explicitly. To get the ListBoxItem you use:

您的对象将始终位于ListBoxItem中,如果您不明确添加它,ListBox将为您生成一个。要获取ListBoxItem,请使用:

var listboxitem = (ListBoxItem)listbox.ItemContainerGenerator.ContainerFromItem(myItem);

#1


28  

Try this:

尝试这个:

ListBoxItem itm = new ListBoxItem();
itm.Content = "some text";

listbox.Items.Add(itm);

listbox is name for ListBox.

listbox是ListBox的名称。

#2


1  

You can do like that

你可以这样做

ListBox1.Items.Insert(0,new ListItem("ITEM 1", "Value"))

#3


0  

Your object will always be in a ListBoxItem, the ListBox will generate one for you if you don't add it explicitly. To get the ListBoxItem you use:

您的对象将始终位于ListBoxItem中,如果您不明确添加它,ListBox将为您生成一个。要获取ListBoxItem,请使用:

var listboxitem = (ListBoxItem)listbox.ItemContainerGenerator.ContainerFromItem(myItem);