Ievgen
Ievgen

Reputation: 4443

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?

Upvotes: 6

Views: 1438

Answers (1)

Julien Lebosquain
Julien Lebosquain

Reputation: 41253

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) }
};

Upvotes: 8

Related Questions