I am trying to change the Control template on a ListBoxItem when It is selected from the ListBox. To do so, I was going to get the selected ListBoxItem from the ListBox itself, and set the control template on that. How would i go about doing this? I have tried, SelectedItem and that returns the bound object within the ListBoxItem.
Asked
Active
Viewed 1.5k times
2 Answers
26
You can retrieve the item container from the bound item by using the ItemContainerGenerator
:
object selectedItem = listBox.SelectedItem;
ListBoxItem selectedListBoxItem = listBox.ItemContainerGenerator.ContainerFromItem(selectedItem) as ListBoxItem;

Thomas Levesque
- 286,951
- 70
- 623
- 758
-
This works but doesn't achieve anything. The "Content" property just returns the selected item object. I don't get the actual cell in the ListBox. – Christian Findlay Jun 26 '18 at 06:00
3
Now you can do it with this:
ListBoxItem container = listBox.ContainerFromIndex(listBox.SelectedIndex) as ListBoxItem;
The ItemContainerGenerator.ContainerFromItem()
function seems like obsolete now.
If you have set the Item Template for the ListBox then you can get it from
UIElement item= container.ContentTemplateRoot;

Anup Sharma
- 2,053
- 20
- 30