获取ListBox中的ListBoxItem

问题描述 投票:13回答:2

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

c# wpf silverlight silverlight-4.0
2个回答
22
投票

您可以使用ItemContainerGenerator从绑定项检索项容器:

object selectedItem = listBox.SelectedItem;
ListBoxItem selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(selectedItem) as ListBoxItem;

2
投票

现在你可以这样做:

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

ItemContainerGenerator.ContainerFromItem()功能现在看起来像obsolete

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

UIElement item= container.ContentTemplateRoot;
© www.soinside.com 2019 - 2024. All rights reserved.