指定的元素已经是另一个元素的逻辑子元素。请先将其断开连接。(解决问题总结)

起因:

<Window x:Class="WpfApplication1.Window3"   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window3" Height="300" Width="300">

    <Window.Resources>

        <Button Background="Blue"  Margin="5" Height="28" x:Key="prev">

            <Image Height="21" Source="Imagesprevious.gif"></Image>

        </Button>

    </Window.Resources>

    <Grid>

        <Button Height="20" Width="70" Content="Content" />

        <StaticResource ResourceKey="prev" />

    </Grid>
<!--第二次-->
     <Grid>

        <Button Height="20" Width="70" Content="Content" />

        <StaticResource ResourceKey="prev" />

    </Grid>

</Window>

报错:

指定的元素已经是另一个元素的逻辑子元素。请先将其断开连接

原因:当实例化的UserControl作为多个父类控件的Content内容时,如果不清除他与前一个父控件的关系,则会报此类错误。

解决方案:

在资源里面添加  x:Shared="False" 就可以了。

 

X:Shared用于指定请求资源时创建实例的两种方式。

X:Shared = “true”(默认):表示所有请求都是共享同一个实例。一般不显示指定。

X:Shared = “false”:表示每次请求都创建一个新的实例。

即:

<Window.Resources>

        <Button Background="Blue" X:Shared = “false” Margin="5" Height="28" x:Key="prev">

            <Image Height="21" Source="Imagesprevious.gif"></Image>

        </Button>

    </Window.Resources>


总结思路来源 http://bbs.csdn.net/topics/370036271
       http://www.cnblogs.com/zlgcool/archive/2008/10/18/1314281.html
原文地址:https://www.cnblogs.com/aguan/p/4903872.html