在 C# 的 ListBox 中添加 ListBoxItem?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13267657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding a ListBoxItem in a ListBox in C#?
提问by Hendra Anggrian
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
采纳答案by Danilo Vulovi?
Try this:
尝试这个:
ListBoxItem itm = new ListBoxItem();
itm.Content = "some text";
listbox.Items.Add(itm);
listbox is name for ListBox.
listbox 是 ListBox 的名称。
回答by Dany
You can do like that
你可以这样做
ListBox1.Items.Insert(0,new ListItem("ITEM 1", "Value"))
回答by Dtex
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);

