Question

If you try to use any shared resources with x:Shared="false" the xaml designer of the Visual Studio 2010 shows you following exception:

System.InvalidOperationException Specified element is already the logical child of another element. Disconnect it first.

Is it possible to workaround it (e.g. by implementing an attached property that does the same creating of the shared object)?

Sample xaml:

<Window.Resources>
    <Image x:Key="SharedImage" x:Shared="false" Source="/Images/image.png" />
    <Style x:Key="ImageButton" TargetType="{x:Type Button}">
        <Setter Property="Content" Value="{StaticResource SharedImage}" />
    </Style>
</Window.Resources>
<StackPanel>
    <Button Style="{StaticResource ImageButton}" />
    <Button Style="{StaticResource ImageButton}" />
</StackPanel>

Is this bug fixed in the Visual Studio 2012?

Was it helpful?

Solution

This isn't considered a bug, unfortunately. Until and unless Microsoft change their minds wrap anything you want shared in a ControlTemplate.

Your example would look something like this (untested):

<Window.Resources>
    <ControlTemplate x:Key="ImageButton">
        <Image Source="/Images/image.png" />
    </ControlTemplate>
    <Style TargetType="Button">
        <Setter Property="Content">
            <Setter.Value>
                <Control Template="{StaticResource ImageButton}"/>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<StackPanel>
    <Button />
    <Button />
</StackPanel>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top