WPF - ItemTemplate not acting as expected

为君一笑 提交于 2019-12-01 06:41:35

It's because it's a list of UIElement, the item template is only applied if the items can't be displayed directly.

Nir is correct, ItemsControl will add item directly to its Panel if they are UIElements. I couldn't find any mention of this behavior in MSDN, but Dr. WPF mentions it in his article on item containers:

If a UIElement is added to the Items collection of an explicit ItemsControl instance (as opposed to an instance of a derived class like ListBox), it will become a direct child of the items panel. If a non-UIElement is added, it will be wrapped within a ContentPresenter.

Your solution is probably to use a ListBox instead, and set ItemContainerStyle to a new Style for ListBoxItem, and in that style, use a ControlTemplate with your Border in it.

Nir is right, this custom ItemsControl implementation will solve the issue and let use your own ItemTemplate:

public class ItemsControlForUIElement : ItemsControl
{
   protected override DependencyObject GetContainerForItemOverride()
   {
       return new ContentPresenter();
   }
   protected override bool IsItemItsOwnContainerOverride(object item)
   {
       return false;
   }
}
Brian

Robert Macnee nailed the reason on the head. His solution involves using the control template which might be overkill for a given scenario. Alternatively, use a ListBox - set the ItemContainerStyle to a new Style for ListBoxItem, and in that style, set the ContentTemplate to the DataTemplate that you wanted to use in the ListBox ItemTemplate.

Steven

If you set the DataType property on the DataTemplate it would start working.

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