Get the ListBoxItem in a ListBox

Ben picture Ben · Aug 24, 2010 · Viewed 12.3k times · Source

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.

Answer

Thomas Levesque picture Thomas Levesque · Aug 24, 2010

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;