Remove Control from Window in WPF

33,005

Every element in the visual tree is either the root of the tree, like a Window, or a child of another element. Ideally you would know which element is the parent of the element you are trying to remove and what type of FrameworkElement it is.

For example, if you have a Canvas and many children and you have a Rectangle that was previously added to the Canvas, you can remove it from the visual tree by removing it from the Canvas like this:

canvas.Children.Remove(control);

But if you don't know who the parent of the control is, you can use the VisualTreeHelper.GetParent Method to find out:

DependencyObject parent = VisualTreeHelper.GetParent(control);

The problem you now face is parent is a DependencyObject and while it is probably also a FrameworkElement, you don't know which kind of element it is. This is important because how you remove the child depends on the type. If the parent is a Button, then you just clear the Content property. If the parent is a Canvas, you have to use Children.Remove.

In general, you can handle the most common cases by checking whether the item is a Panel and then remove from its children, otherwise if it is a ContentControl (like a Window) then set its Content property to null. But this isn't foolproof; there are other cases.

You also have to be careful not to remove something that is expanded from a template because that is not a static content you can modify at will. If you added the control or existed in static XAML, you can safely remove it.

Share:
33,005
Casebash
Author by

Casebash

Bachelor of Science (Adv Maths) with Honors in Computer Science from University of Sydney Programming C/C++/Java/Python/Objective C/C#/Javascript/PHP

Updated on July 09, 2022

Comments

  • Casebash
    Casebash almost 2 years

    How can I remove a control from a window in WPF? RemoveLogicalChild only removes it as a logical child, but leaves it still visible.

  • Mike Two
    Mike Two over 11 years
    I'm not sure how checking the parent type through this method will help.