Silverlight用户控件转移时产生的“元素已经是另一个元素的子元素”问题
最近的项目中遇到了silverlight用户控件由一个canvas转移到另一个canvas的问题,在转移的过程中一直提示“元素已经是另一个元素的子元素”,十分讨厌,调试了多次也没有找到原因所在,情况如下
1,简单的移动
LayerTwo是一个usercontrol,mainpage.xaml上呢有两个canvas,其中一个放的有LayerTwo,
代码
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Height="100" HorizontalAlignment="Left" Margin="24,25,0,0" Name="canvas1" VerticalAlignment="Top" Width="200" >
<layer:LayerTwo x:Name="uc" Canvas.Left="3" Canvas.Top="-130"></layer:LayerTwo>
</Canvas>
<Canvas Height="100" HorizontalAlignment="Left" Margin="24,140,0,0" Name="canvas2" VerticalAlignment="Top" Width="200" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="266,117,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
<Canvas Height="100" HorizontalAlignment="Left" Margin="24,25,0,0" Name="canvas1" VerticalAlignment="Top" Width="200" >
<layer:LayerTwo x:Name="uc" Canvas.Left="3" Canvas.Top="-130"></layer:LayerTwo>
</Canvas>
<Canvas Height="100" HorizontalAlignment="Left" Margin="24,140,0,0" Name="canvas2" VerticalAlignment="Top" Width="200" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="266,117,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
我们如果将layertwo从canvas1中转移到canvas2中,只需要
UserControl uc = this.canvas1.Children[0] as UserControl;
this.canvas1.Children.RemoveAt(0);
this.canvas2.Children.Add(uc);
this.canvas1.Children.RemoveAt(0);
this.canvas2.Children.Add(uc);
2,如果usercontrol是放在嵌套的canvas中或者是其他的usercontrol中呢?
如果我们将上面的例子简单的改变一下,在canvas1中再增加一层canvas3,layerTwo.xaml放在canvas3中,如果想把layerone.xaml转移到canvas2中怎么做呢?
代码
Canvas c = this.canvas2.Children[0] as Canvas;
UserControl uc = c.Children[0] as UserControl;
this.canvas2.Children.RemoveAt(0);
this.canvas1.Children.Add(uc);
UserControl uc = c.Children[0] as UserControl;
this.canvas2.Children.RemoveAt(0);
this.canvas1.Children.Add(uc);
这种做法就是直接将内层的canvas去掉,按说内层的canvas去掉后,里面的usercontrol应该也没有了,但是当我们添加获取的usercontrol到canvas1时,发现“元素已经是另一个元素的子元素”这个恼人的提示,debug后发现这个usercontrol居然还有parent父级对象,于是在usercontrol的最直接上级canvas3 再次执行了removeat的方法才得以通过。
this.canvas2.Children.RemoveAt(0);
//换成这样
c.Children.RemoveAt(0);
类似的用户控件使用必须确保此用户控件的父级对象为空,执行remove此用户控件后再添加到其他地方,否则是添加不了的。