获取ListBox中的ListBoxItem

时间:2010-08-24 12:16:10

标签: c# wpf silverlight silverlight-4.0

当我从ListBox中选择它时,我试图更改ListBoxItem上的Control模板。为此,我将从ListBox本身获取选定的ListBoxItem,并在其上设置控件模板。我该怎么做呢?我试过,SelectedItem并返回ListBoxItem中的绑定对象。

2 个答案:

答案 0 :(得分:22)

您可以使用ItemContainerGenerator

从绑定项中检索项容器
object selectedItem = listBox.SelectedItem;
ListBoxItem selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(selectedItem) as ListBoxItem;

答案 1 :(得分:2)

现在你可以这样做:

ListBoxItem container = listBox.ContainerFromIndex(listBox.SelectedIndex) as ListBoxItem;

ItemContainerGenerator.ContainerFromItem()函数现在似乎是obsolete

如果您已为ListBox设置了项目模板,那么您可以从

获取它
UIElement item= container.ContentTemplateRoot;
相关问题