Tim Hibbard

CEO for EnGraph software
posts - 628 , comments - 1632 , trackbacks - 459

My Links

News



Add to Google

Twitter












Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

EnGraph Blogs

Links

Other

Roll

WPF - Get ListBoxItem from ListBox.SelectedItem

I had some trouble today getting the actual control that hosts data in a WPF listbox.  The magic class is ListBox.ItemContainerGenerator used like this:

MyStateObject current = this.myListBox.SelectedItem as MyStateObject;
ListBoxItem lbi = this.myListBox.ItemContainerGenerator.ContainerFromItem(current) as ListBoxItem;
lbi.Margin = new Thickness(10);

 

Technorati tags: , , ,

Print | posted on Wednesday, February 13, 2008 2:01 PM | Filed Under [ .NET WPF ]

Feedback

Gravatar

# re: WPF - Get ListBoxItem from ListBox.SelectedItem

I'm very glad you found this out and google found you. someone ought to write a book on WPF Magic Snippets - the things you always want to do but are never easy to find.

Thanks
8/15/2009 5:11 PM | Pete Maher
Gravatar

# re: WPF - Get ListBoxItem from ListBox.SelectedItem

This is a very useful piece of code which saved me the trouble of having to intercept the mouse clicks to determine the listboxitem selected. Since I am a VB programer, I converted the code to a VB as an Extension Method so that in can be accessed as a method of listbox. The code is attached below if anyone is interested in it. The code was written in .Net 4.0 Beta 1 but it should work in .Net 3.5

<Extension()> _
Public Function SelectedListboxItem(ByVal lbx As ListBox) As ListBoxItem
If lbx.SelectedIndex > -1 _
Then
Return CType(lbx.ItemContainerGenerator.ContainerFromItem (lbx.SelectedItem), ListBoxItem)
Else
Return Nothing
End If
End Function

You can access the extension method as follows:

Dim lbi As ListBoxItem = lbx.SelectedListboxItem
9/3/2009 8:21 AM | Rich Drennan
Gravatar

# re: WPF - Get ListBoxItem from ListBox.SelectedItem

Thanks Rich - Great addition!
9/3/2009 9:31 AM | Tim Hibbard
Gravatar

# re: WPF - Get ListBoxItem from ListBox.SelectedItem

Why do you use a own type?

ListBoxItem lbi = (ListBoxItem)myListBox.SelectedItem;
12/17/2010 6:28 AM | visitor
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: