我有一系列可以传递的控件,有时它们会作为子项添加到另一个控件中。
在许多情况下,我无法确定控件当前是否是另一个控件的子控件。
例如:
Label lbl = new Label( );
/*Stuff happens; lbl may be assigned or not; whatever.*/
//If the label has already been assigned as a child to a viewbox
if ( lbl.Parent is Viewbox )
return lbl.Parent;
else {
if (lbl.Parent != null )
//Of course this fails because there is no lbl.Parent.Child property.
lbl.Parent.Child = null;
return new Viewbox( ) { Child = lbl, Stretch = Stretch.Uniform };
}
完全有可能我完全误解了Control.Parent属性的功能。
是否可以通过控件本身从它的父级中删除一个控件?
答案 0 :(得分:1)
void RemoveElementFromItsParent(FrameworkElement el)
{
if (el.Parent == null)
return;
var panel = el.Parent as Panel;
if (panel != null)
{
panel.Children.Remove(el);
return;
}
var decorator = el.Parent as Decorator;
if (decorator != null)
{
decorator.Child = null;
return;
}
var contentPresenter = el.Parent as ContentPresenter;
if (contentPresenter != null)
{
contentPresenter.Content = null;
return;
}
var contentControl = el.Parent as ContentControl;
if (contentControl != null)
contentControl.Content = null;
}