如何获取WPF ItemsControl的常规ItemContainer类型

Iev*_*ida 5 silverlight wpf user-controls itemscontrol wpf-controls

我想确定ItemContainer现有ItemsControl对象的类型.

   var item = control as ItemsControl;
    //HOW to get child container Type?
Run Code Online (Sandbox Code Playgroud)

示例混合如何做到这一点:

在此输入图像描述

Blend以某种方式确定当前TabControl类型的子项是TabItem.

如何在代码中做同样的事情?

Jul*_*ain 8

有一个StyleTypedPropertyAttribute从派生类的大部分ItemsControl.得到一个Property等于的人"ItemContainerStyle".在StyleTargetType此属性属性应该给你的项目类型.

请注意,您必须注意不要从基类获取属性.此外,虽然这适用于大多数类型(TabControl,ListBox),但某些类(例如,DataGrid根本没有使用此属性进行注释).

这是我用于内置框架类型的列表:

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) }
};
Run Code Online (Sandbox Code Playgroud)