Blog

WPF: How to get ListboxItem from selected entity

Posted by Nipun Tomar Blogs | WPF 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.
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.
Employers - Post Free Jobs
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.