Bjö*_*örn 21 c# wpf logical-tree
我有一个控件是另一个控件的子控件(因为所有非root控件/元素都在WPF中).如果我想将控件移动到另一个容器,我必须先将它与当前容器断开连接(否则抛出异常).
如果我知道父母是什么,那么我可以将它从其儿童收藏品,内容或其他内容中删除.但是,如果我不知道父容器的类型是什么 - 如何删除子控件呢?
在下面的代码示例中:如何在不知道父类型(Panel,GroupBox ...)的情况下将"sp1"移动到另一个容器?
// Add the child object "sp1" to a container (of any type).
StackPanel sp1 = new StackPanel();
SomeParentControl.Children.Add(sp1);
// Somewhere else in the code. I still have a reference to "sp1" but now I don't know what container it is in. I just want to move the "sp1" object to another parent container.
AnotherParentControl.Content = sp1; // Generates exception: "Must disconnect specified child from current parent Visual before attaching to new parent Visual."
Run Code Online (Sandbox Code Playgroud)
理想情况下,我只想写一些类似的东西:
sp1.Parent.RemoveChild(sp1);
Run Code Online (Sandbox Code Playgroud)
但我还没有找到类似的东西.
Cle*_*ens 21
您可以使用扩展方法编写辅助类:
public static class RemoveChildHelper
{
public static void RemoveChild(this DependencyObject parent, UIElement child)
{
var panel = parent as Panel;
if (panel != null)
{
panel.Children.Remove(child);
return;
}
var decorator = parent as Decorator;
if (decorator != null)
{
if (decorator.Child == child)
{
decorator.Child = null;
}
return;
}
var contentPresenter = parent as ContentPresenter;
if (contentPresenter != null)
{
if (contentPresenter.Content == child)
{
contentPresenter.Content = null;
}
return;
}
var contentControl = parent as ContentControl;
if (contentControl != null)
{
if (contentControl.Content == child)
{
contentControl.Content = null;
}
return;
}
// maybe more
}
}
Run Code Online (Sandbox Code Playgroud)