WPF: How to get ListboxItem from selected entity

By Nipun Tomar Nov 04, 2011
There will be some scenarios where we need to get the object of ListBoxItem which is hosting one of the the bound entity
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.
Nipun Tomar

Nipun is competent and experienced project leader, with 9 years of experience in managing multi-disciplinary teams of varying sizes and complex programs of work. Has the ability to build strong relationships wit... Read more

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs