日期:2014-05-17  浏览次数:21177 次

WPF,请问ListBox的项
MSDN上面说到,ListBox包含 ListBoxItem对象的集合。我对下面两段代码进行了测试:

前台有一个ListBox控件:

<ListBox Name="listbox1" />


listbox1.Items.Add("张三");
MessageBox.Show(listbox1.Items[0].GetType().ToString());

添加了数据之后,通过输出项的类型,输出的类型为string类型。请问,这里面包含ListBoxItem吗?是不是ListBox的项都是由ListBoxItem来包装的呢?

如果前台是这样的:

<ListBox Name="listbox1">
    <ListBoxItem Content="张三"/>
</ListBox>

这样的话,在后台输出项的类型,输出的是ListBoxItem类型。

我想问的是,是不是ListBox的项都是由ListBoxItem来包装的呢?如果是的话,第一段代码也应该有ListBoxItem的吧,类型也应该是ListBoxItem的吧,为什么输出不是ListBoxItem类型的呢?

------解决方案--------------------
listbox.Items集合允许你添加object类型,也就是任意类型。
------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/system.windows.controls.itemscontrol.items(v=vs.100).aspx

http://msdn.microsoft.com/zh-cn/library/system.windows.controls.itemcollection(v=vs.100).aspx

http://msdn.microsoft.com/zh-cn/library/system.windows.controls.itemcollection.item(v=vs.100).aspx

public Object this[
int index
] { get; set; }

http://msdn.microsoft.com/zh-cn/library/system.windows.controls.itemcollection.add(v=vs.100).aspx

public int Add(
Object newItem
)
------解决方案--------------------
<ListBoxItem?Content="张三"/> 的Content可以是任意对象,具体要显示成什么 由你来决定,你可以转转换器属性修改
------解决方案--------------------
视觉树包含逻辑树不包含。
不管你往ListBox中添加什么数据,显示出来时,每一项都是放在ListBoxItem这个容器中。但数据本身和ListBoxItem无关,你用的是什么就是什么。