I have a UserControl
which I\'m using to display a list of UIElement
s. The control consists of a single ItemsControl
with it\'s
If you set the DataType
property on the DataTemplate
it would start working.
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 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;
}
}
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.
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
.