13

I would like to remove a FrameworkElement from the visual tree. Since the FrameworkElement has a Parent property, it would be obvious to solve this problem by removing it from there:

FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
   // This line will, of course not complie:
   // childElement.Parent.RemoveFromChildren(childElement);
}

The problem is that the Parent property of FrameworkElement is of DependencyObject, which has no notion of children. So the only thing I can see going about this problem is via casting the Parent to see if it's a Border, Panel etc (elements that have notion of children) and remove it from there:

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;
   }
}

Obviously this is not a very flexible solution and not generic at all. Can someone suggest a more generic approach on removing an element from the visual tree?

4

1 回答 1

7

我认为没有更简单的方法。实际上,不可能有一个简单的通用方法来做到这一点。WPF非常灵活,您可以使用模板创建自定义控件,该模板需要 3 个子项使用自定义模板在 3 个不同的位置显示。

您能做的最好的事情是考虑所有基本控件并将它们包含在您的if-else梯子中。这些是Panel, Border, ContentControl,ItemsControl等。

于 2010-12-09T10:00:43.627 回答