如何获取WPF ItemsControl的常规ItemContainer类型 [英] How to get general ItemContainer type for WPF ItemsControl
问题描述
我想从现有的ItemsControl
对象确定ItemContainer
类型.
I want to determine ItemContainer
type from an existing ItemsControl
object.
var item = control as ItemsControl;
//HOW to get child container Type?
如何通过Blend完成此操作的示例:
An example of how it's done by a Blend:
混合以某种方式确定当前TabControl
类型的子项是TabItem
.
Blend somehow determines that the current TabControl
type child item is TabItem
.
如何在代码中做同样的事情?
How to do the same thing in code?
推荐答案
有一个 StyleTypedPropertyAttribute
在大多数从ItemsControl
派生的类上.获得具有Property
等于"ItemContainerStyle"
的那个.该属性的StyleTargetType
属性应为您提供商品类型.
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.
请注意,您必须注意不要从基类中获取属性.另外,虽然这适用于大多数类型(TabControl
,ListBox
),但是某些类(例如DataGrid
)根本没有使用此属性进行注释.
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) }
};
这篇关于如何获取WPF ItemsControl的常规ItemContainer类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!