问题
I want to determine ItemContainer
type from an existing ItemsControl
object.
var item = control as ItemsControl;
//HOW to get child container Type?
Example how blend does this:

Blend somehow determines that current TabControl
type child item is TabItem
.
How to do same thing in code?
回答1:
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) }
};
来源:https://stackoverflow.com/questions/12436992/how-to-get-general-itemcontainer-type-for-wpf-itemscontrol