我想从可视树中移除一个 FrameworkElement。由于 FrameworkElement 具有 Parent 属性,因此通过从该属性中删除它来解决这个问题是显而易见的:
FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
// This line will, of course not complie:
// childElement.Parent.RemoveFromChildren(childElement);
}
问题在于FrameworkElement的Parent属性是DependencyObject类型,它没有子元素的概念。所以我能想到的唯一解决方法是通过将Parent强制转换为Border、Panel等(有子元素概念的元素)来查看并从那里移除:
FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
if(childElement.Parent is Panel)
{
(childElement.Parent as Panel).Children.Remove(childElement );
}
if(childElement.Parent is Border)
{
(childElement.Parent as Border).Child = null;
}
}
显然这不是一个很灵活的解决方案,也不是通用的。有人能建议一种更通用的方法来从可视树中移除一个元素吗?