Why does the Parent property of a container of an ItemsControl return null and not the Panel it sits on?

I never noticed that and this spiked my curiosity. After looking for clues in the .Net Framework in found that Parent property seems indeed to be set manualy: This required several steps but I found that the only way to change the parent property is to invoke these methods:

parent affectation

If I analyse for example the FrameworkElement.AddLogicalChild method, I found that these methods are using it:

FrameworkElement.AddLogicalChild analysis

This confirms that the parent property is supposed to refer to the logical tree. I tried to create my own custom control:

[ContentProperty("CustomContent")]
public class CustomControl1 : Control
{
    static CustomControl1()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
    }

    public object CustomContent
    {
        get { return GetValue(CustomContentProperty); }
        set { SetValue(CustomContentProperty, value); }
    }

    public static readonly DependencyProperty CustomContentProperty = DependencyProperty.Register("CustomContent", typeof(object), typeof(CustomControl1));
}

with this template:

<ControlTemplate TargetType="{x:Type local:CustomControl1}">
     <ContentPresenter ContentSource="CustomContent" />
</ControlTemplate>

I used it this way:

<WpfApplication1:CustomControl1 Width="50" Height="50">
    <Rectangle Fill="Red" />
</WpfApplication1:CustomControl1>

... this worked like this (like a charm :-)):

custom control screen caprute

... and guess what... Parent of the rectangle is not set :-)

I don't have time to continue investigating for now but regarding ItemsControl, I imagine that maybe the ItemContainerGenerator doesn't know the logical parent in which it inserts itemsContainers, that could explain why parent property is not set in this case... but that need to be proven...


The FrameworkElement.Parent property documentation says it may be null e.g. for items created in datatemplates. In such case they propose using FrameworkElement.TemplatedParent:

For templates, the Parent of the template eventually will be null. To get past this point and extend into the logical tree where the template is actually applied, use TemplatedParent.

May be it's your case? It helped me in similar case (I used Parent then if it's null used TemplateParent as fallback).

Yes, the answer is late but it may help others who stumbles on same error as me