WPF - ItemTemplate not acting as expected

后端 未结 5 2027
野的像风
野的像风 2021-01-14 02:25

I have a UserControl which I\'m using to display a list of UIElements. The control consists of a single ItemsControl with it\'s

相关标签:
5条回答
  • 2021-01-14 02:45

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

    0 讨论(0)
  • 2021-01-14 02:47

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

    0 讨论(0)
  • 2021-01-14 02:47

    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;
       }
    }
    
    0 讨论(0)
  • 2021-01-14 02:52

    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.

    0 讨论(0)
  • 2021-01-14 03:03

    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.

    0 讨论(0)
提交回复
热议问题