Removing an item from the visual tree in a generic way
Asked Answered
S

1

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?

Semester answered 9/12, 2010 at 9:52 Comment(0)
U
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.

Undry answered 9/12, 2010 at 10:0 Comment(2)
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!Semester
@Gergely: I came across an article on MSDN about content model in WPF. I though this might be useful for you. msdn.microsoft.com/library/bb613548.aspxUndry

© 2022 - 2024 — McMap. All rights reserved.