Casebash
Casebash

Reputation: 118742

Remove Control from Window in WPF

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

Upvotes: 22

Views: 38125

Answers (3)

luka
luka

Reputation: 637

you can use this to remove a child from ,in this case, a canvas.

private void RemoveControl()
{
   name = myUserControl.GetValue(NameProperty).ToString();               
   myCanvas.Children.Remove(myUserControl);
   NameScope.GetNameScope(this).UnregisterName(name);
}

Upvotes: 0

Emile Nouatin
Emile Nouatin

Reputation: 1

To check the parent type , You can also use the GetType Method adding toString Method and compare. For example , the string "System.Windows.Controls.Canvas" will be returned when the parent Object is a canvas

Upvotes: 0

Rick Sladkey
Rick Sladkey

Reputation: 34240

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.

Upvotes: 33

Related Questions