How to get general ItemContainer type for WPF ItemsControl

拟墨画扇 提交于 2019-12-23 10:17:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!