I want to determine ItemContainer
type from an existing ItemsControl
object.
var item = control as ItemsControl;
//HOW to get child container Type?
An example of how it's done by a Blend:
Blend somehow determines that the current TabControl
type child item is TabItem
.
How to do the same thing in code?
There is a StyleTypedPropertyAttribute
on most classes derived from ItemsControl
. Get the one having Property
equals to "ItemContainerStyle"
. The StyleTargetType
property on this attribute should give you the item type.
Note that you have to be careful not to get attribute from the base class. Also, while this works for most types (TabControl
, ListBox
), some classes such as DataGrid
are simply not annotated with this attribute.
Here is the list I use for built-in framework types:
var _itemsContainerTypeByContainerType = new Dictionary<Type, Type> {
{ typeof(ComboBox), typeof(ComboBoxItem) },
{ typeof(ContextMenu), typeof(MenuItem) },
{ typeof(DataGrid), typeof(DataGridRow) },
{ typeof(DataGridCellsPresenter), typeof(DataGridCell) },
{ typeof(DataGridColumnHeadersPresenter), typeof(DataGridColumnHeader) },
{ typeof(HeaderedItemsControl), typeof(ContentPresenter) },
{ typeof(ItemsControl), typeof(ContentPresenter) },
{ typeof(ListBox), typeof(ListBoxItem) },
{ typeof(ListView), typeof(ListViewItem) },
{ typeof(Menu), typeof(MenuItem) },
{ typeof(MenuBase), typeof(MenuItem) },
{ typeof(MenuItem), typeof(MenuItem) },
{ typeof(MultiSelector), typeof(ContentPresenter) },
{ typeof(Selector), typeof(ContentPresenter) },
{ typeof(StatusBar), typeof(StatusBarItem) },
{ typeof(TabControl), typeof(TabItem) },
{ typeof(TreeView), typeof(TreeViewItem) },
{ typeof(TreeViewItem), typeof(TreeViewItem) }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With