Why Does ItemsControl Not Use My ItemTemplate?

前端 未结 2 1110
挽巷
挽巷 2020-12-11 02:36

I am able to use an ItemTemplate within an ItemsControl to render items in a specific format. However, if one of the items within the ItemsControl happens to be, say, a Tex

相关标签:
2条回答
  • 2020-12-11 03:01

    I'm just speculating here, but I would bet that it's behavior that lives inside of the ItemContainerGenerator. I'd bet that the ItemContainerGenerator looks at an item, and if it's a UIElement it says, "cool, the item container's been generated, I'll just return it" and if it's not, it says, "I'd better generate a container for this item. Where's the DataTemplate?"

    0 讨论(0)
  • 2020-12-11 03:14

    The ItemsControl has a protected member IsItemItsOwnContainerOverride which is passed an object from the items collection and returns true if that object can be added directly to the items panel without a generated container (and thereby be templated).

    The base implementation returns true for any object that derives from UIElement.

    To get the behaviour you would expect you would need to inherit from ItemsControl and override this method and have it always return false. Unfortunately thats not the end of the matter. The default implementation of PrepareContainerForItemOverride still doesn't assign the ItemTemplate to the container if the item is a UIElement so you need to override this method as well:-

        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return false;
        }
    
    
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            ((ContentPresenter)element).ContentTemplate = ItemTemplate;
        }
    
    0 讨论(0)
提交回复
热议问题