Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get general ItemContainer type for WPF ItemsControl

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:

enter image description here

Blend somehow determines that the current TabControl type child item is TabItem.

How to do the same thing in code?

like image 488
Ievgen Avatar asked Sep 15 '12 11:09

Ievgen


1 Answers

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) }
};
like image 193
Julien Lebosquain Avatar answered Nov 13 '22 01:11

Julien Lebosquain