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.
post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter