我正在尝试从ListBox中选择它时更改ListBoxItem上的Control模板。为此,我将从ListBox本身获取选定的ListBoxItem,并在其上设置控件模板。我该怎么做呢?我试过,SelectedItem并返回ListBoxItem中的绑定对象。
您可以使用ItemContainerGenerator
从绑定项检索项容器:
object selectedItem = listBox.SelectedItem;
ListBoxItem selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(selectedItem) as ListBoxItem;
现在你可以这样做:
ListBoxItem container = listBox.ContainerFromIndex(listBox.SelectedIndex) as ListBoxItem;
ItemContainerGenerator.ContainerFromItem()
功能现在看起来像obsolete。
如果您已为ListBox设置了项目模板,那么您可以从中获取它
UIElement item= container.ContentTemplateRoot;