Geeks With Blogs

News



Add to Google

Tim Hibbard CEO for EnGraph software

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: , , ,
Posted on Wednesday, February 13, 2008 2:01 PM .NET , WPF | Back to top


Comments on this post: WPF - Get ListBoxItem from ListBox.SelectedItem

# re: WPF - Get ListBoxItem from ListBox.SelectedItem
Requesting Gravatar...
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
Left by Pete Maher on Aug 15, 2009 5:11 PM

# re: WPF - Get ListBoxItem from ListBox.SelectedItem
Requesting Gravatar...
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
Left by Rich Drennan on Sep 03, 2009 8:21 AM

# re: WPF - Get ListBoxItem from ListBox.SelectedItem
Requesting Gravatar...
Thanks Rich - Great addition!
Left by Tim Hibbard on Sep 03, 2009 9:31 AM

# re: WPF - Get ListBoxItem from ListBox.SelectedItem
Requesting Gravatar...
Why do you use a own type?

ListBoxItem lbi = (ListBoxItem)myListBox.SelectedItem;
Left by visitor on Dec 17, 2010 6:28 AM

Your comment:
 (will show your gravatar)


Copyright © Tim Hibbard | Powered by: GeeksWithBlogs.net