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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…