Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...