How to get generic ItemContainer type for WPF ItemsControl

I want to determine the type of ItemContainer from an existing ItemsControl .

  var item = control as ItemsControl; //HOW to get child container Type? 

Blend usage example:

enter image description here

Blend somehow determines that the current TabControl a child of the TabItem .

How to do the same in code?

+5
source share
1 answer

In most classes derived from ItemsControl , there is a StyleTypedPropertyAttribute . Get a value that has Property equal to "ItemContainerStyle" . The StyleTargetType property of this attribute should indicate the type of element.

Note that you must be careful not to get the attribute from the base class. In addition, although this works for most types ( TabControl , ListBox ), some classes, such as DataGrid , simply are not annotated with this attribute.

Here is the list I use for the built-in frame 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) } }; 
+8
source

All Articles