Getting ListBoxItem from selected entity:
There will be some scenarios where we need to get the object of ListBoxItem which is hosting one of the the bound entity.Most probably it may be the SelectedItem.
Consider this scenario there is an business class called Employee and it's collection class is EmployeeCollection.We have binding which binds object of EmployeeCollection to a ListBox.If we access the SelectedItem property of ListBox it will return the Employee object.But the requirement is to get the ListBoxItem which hosts the selected entity on an event say SelectionChanged.
Code in VB.Net:
Dim lbi As ListBoxItem = lstBox.ItemContainerGenerator.ContainerFromItem(lstBox.SelectedItem)
Code in C#:
ListBoxItem lbi = lstBox.ItemContainerGenerator.ContainerFromItem(lstBox.SelectedItem);
Note: The above code can be used to get ListBoxItem of any object which is present in the collection.