WPF Error: Specified element is already the logical child of another element. Disconnect it first.

July 17, 2011

The first time I saw this error, it completely threw me off. I had a ContentControl and in the style for it I was setting the Content to a wrapper for the ContentPresenter.

<Style x:Key="MyCustomContentControl" 
       TargetType="{x:Type ContentControl}">
    <Setter Property="Content">
        <Setter.Value>
            <local:MyCustomControl>
                <ContentPresenter />
            </local:MyCustomControl>
        </Setter.Value>
    </Setter>
</Style>

I would get this error whenever more than one ContentControl implemented this style.

I finally realized the error was telling me exactly what the issue was, I was just too blind to realize it. I was setting the Content, not the ContentTemplate. The specified element (MyCustomControl) was already the child of one ContentControl, so I could not add it as a child to another one.

I needed to switch my style to set the ContentTemplate, not the Content of my ContentControl. The way I currently had it written was like giving multiple people the same cookie to eat. It just didn’t work. Instead I needed to give them the cookie cutter so they could all make their own cookies, which is why I needed to set the Template instead of the Content.

<Style x:Key="MyCustomContentControl" 
       TargetType="{x:Type ContentControl}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <local:MyCustomControl>
                <ContentPresenter />
            </local:MyCustomControl>
        </Setter.Value>
    </Setter>
</Style>