Removing an item from the visual tree in a generic way

Gergely Orosz picture Gergely Orosz · Dec 9, 2010 · Viewed 8.6k times · Source

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?

Answer

decyclone picture decyclone · Dec 9, 2010

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.