How can I remove a control from a window in WPF? RemoveLogicalChild only removes it as a logical child, but leaves it still visible.
How can I remove a control from a window in WPF? RemoveLogicalChild only removes
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 ofFrameworkElementit is.For example, if you have a
Canvasand many children and you have aRectanglethat was previously added to theCanvas, you can remove it from the visual tree by removing it from theCanvaslike this:But if you don’t know who the parent of the control is, you can use the VisualTreeHelper.GetParent Method to find out:
The problem you now face is
parentis aDependencyObjectand while it is probably also aFrameworkElement, 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 aButton, then you just clear theContentproperty. If the parent is aCanvas, you have to useChildren.Remove.In general, you can handle the most common cases by checking whether the item is a
Paneland then remove from its children, otherwise if it is aContentControl(like aWindow) then set itsContentproperty tonull. 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.