views:

834

answers:

1

hi there,

i created a ListBox that has a DataTemplate as Itemtemplate. however, is there an easy way to access the generated UIElement instead of SelectedItem in codebehind?

when i access SelectedItem i just get the selected object from my ItemsSource collection. Is there a way to access the UIElement (ie. the element generated from the DataTemplate together with the bound object)? any ideas? thanks

+4  A: 

You are looking for the ItemContainerGenerator property. Each ItemsSource has an ItemContainerGenerator instance. This class has the following method that might interest you: ContainerFromItem(object instance).

Once you have a handle to the ListBoxItem, you can go ahead and browse the logical and visual tree. Check out Logical Tree Helper and Visual Tree Helper.

Like Andy said in the comments, just because the item exists in your collection doesn't mean a container has been generated for it. Any kind of virtualizing panel scenario will raise this issue; UIElements will be reused across the different items. Be careful with that as well.

siz
Note that just because an item has been added to the control, that doesn't mean that its UI container has been generated yet. Make sure to account for the case where there is no UI container yet.
Andy
I am writing in c# and WPF and this property doesn't appear under ListBox.ItemsContainer How do I get the instance for this listbox?
sprite