'Element is already the child of another element' error in Silverlight App.xaml

Ronald Wildenberg picture Ronald Wildenberg · Nov 13, 2009 · Viewed 17k times · Source

I keep getting a strange error inside my App.xaml file:

Element is already the child of another element.

My App.xaml file looks like this:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="Celerior.Annapurna.SL.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ProvisiorResourceDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

The error is reported for the entire ResourceDictionary element (from lines 5 to 9).

ProvisiorResourceDictionary.xaml contains a number of styles and templates. Nothing exciting in my opinion.

Does anyone know what is wrong?

Kind regards,

Ronald Wildenberg

Answer

Ronald Wildenberg picture Ronald Wildenberg · Nov 13, 2009

I found the cause of the problem myself, thanks to the hints provided in the comment by AnthonyWJones.

It appears everything inside a Silverlight resource dictionary must be shareable. The reason is that items inside a resource dictionary will (probably) be added at multiple locations in the control hierarchy.

I had two items inside my resource dictionary that were not shareable.

EDIT: In WPF, you can use the x:Shared attribute on objects inside a resource dictionary to force WPF to create a new instance for every resource retrieval. Unfortunately, Silverlight does not support this attribute.