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?

Gergely Orosz
  • 6,475
  • 4
  • 47
  • 59

1 Answers1

7

I don't think there is a simpler way. Actually, there cannot be an easy generic way to do that. WPF is very flexible and you can create a custom control with a template that takes 3 children to display in 3 different places with custom templates.

What you can do best is take into account all the basic controls and include them in you if-else ladder. These are Panel, Border, ContentControl, ItemsControl, etc.

decyclone
  • 30,394
  • 6
  • 63
  • 80
  • Shame there's are no general interfaces for items with children. Thanks for the list, I haven't thought of ContentControl or ItemsControl... for now this will do! – Gergely Orosz Dec 11 '10 at 21:14
  • 3
    @Gergely: I came across an article on MSDN about content model in WPF. I though this might be useful for you. http://msdn.microsoft.com/library/bb613548.aspx – decyclone Dec 27 '10 at 05:42