C# WPF中用代码移动控件

用代码移动控件时,容易出现报错:指定的元素已经是另一个元素的逻辑子元素。请先将其断开连接。

这个报错说的很清楚,就是被移动控件必须从原位置中移出,才能放入新位置。WinForm中没有这个限制,刚接触WPF的朋友就会不知道怎么解决。

按照提示,理论上我们只要使用如下代码即可顺利完成移动:

1、被移动控件父控件.Children.Remove(被移动控件);

2、目标控件.Children.Add(被移动控件);

但是,不是所有控件都有Children属性的,有的元素只有Child。我们看一下布局文件:

<StackPanel x:Name="spanMonitor" Grid.Row="0">
    <Border x:Name="imageMonitorBorder" Background="Black" Margin="5" Height="220">
        <Image x:Name="imageMonitor" Margin="5" MouseLeftButtonDown="imageMonitor_MouseLeftButtonDown" />
    </Border>
</StackPanel>

imageMonitorBorder是个Border控件,它虽然“包裹”着image控件,但它只有Child,无法移除子控件。

spanMonitor是个StackPanel,它有Children,可以移出移入子控件。

这样我们移动imageMonitor时,需要带着imageMonitorBorder一起移动就行了。

Border Border = this.imageMonitorBorder;
this.spanMonitor.Children.Remove(Border);
formMonitorFullScreen.spanMonitorFullScreen.Children.Add(Border);

作为布局控件,如Grid、StackPanel……都是有Children的,因此控件的移动需要在这个层面上进行。

猜你喜欢

转载自blog.csdn.net/dgnankai/article/details/129064867