Can you get the container type from a given ItemContainerGenerator?

136 Views Asked by At

Given an arbitrary ItemsControl, is it possible to get the type of the container objects which its ItemContainerGenerator creates/uses?

For example, given a ListBox, I'm trying to get the type ListBoxItem. For a TreeView, it would be TreeViewItem, etc.

I'm trying to find a generic solution for any ItemsControl (or more accurately, any control which utilizes an ItemContainerGenerator.)

I'm specifically looking for the Type, not an instance of the type, nor would I like to rely on creating an instance just to check its type.

1

There are 1 best solutions below

6
SledgeHammer On

There are two ways :)

1) you'll need to use reflection or expression trees to call the method since its protected. GetContainerForItemOverride() will return a DependencyObject and then you can use GetType() on that.

2) Or you can call something like treeView.ItemContainerGenerator.ContainerFromIndex(0) to get the container for the 0 item, but that'll only work if you have at least one item in the tree (or control).