views:

246

answers:

2

The actual visuals are dictated by a DataTemplate. In runtime, how can I iterate through all the visual elements of a ListBoxItem?

+2  A: 

Assuming that you have a reference to one of the ListBoxItems in the list, you can use the VisualTreeHelper class to enumerate the visual tree of it.

Otherwise, if you have a reference to one of the items displayed in the ListBox, try calling ItemContainerGenerator.ContainerFromItem() off of the ListBox (note that the item must be displayed for this to work, since the ListBox generally only keeps items that are visible in memory).

Andy
There is an example at http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.aspx
Qwertie
This answer does not work for me with an ItemsControl. After inserting a new item at index 0, I can do the following:var presenter = (ContentPresenter)_itemsControl.ItemContainerGenerator.ContainerFromIndex(0);Unfortunately, VisualTreeHelper.GetChildrenCount(presenter) is zero!
Qwertie
I made a quick test app, and that worked for me. You might want to post a new question and provide more info.
Andy
A: 

Keep aside the reason why you need to do so....

I think you need the VisualTreeHelper class for this.

Gishu