我如何删除从WPF窗口的控制? RemoveLogicalChild
只删除它作为一个逻辑子,但保留它仍然可见。
How can I remove a control from a window in WPF? RemoveLogicalChild
only removes it as a logical child, but leaves it still visible.
在可视化树的每一个元素是树的每根,就像窗口
或另一种元素的子。理想情况下,你会知道哪些因素是您要删除什么 FrameworkElement的
的类型是元素的父。
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.
例如,如果你有一个画布
和许多孩子和你有一个矩形
这是previously添加到画布
,你可以从可视化树中删除从取出的画布
是这样的:
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);
但如果你不这样做的知道谁控制的母公司是,你可以使用VisualTreeHelper.GetParent法找出:
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);
您现在面临的问题是父
是的DependencyObject
键,而这大概也是一个 FrameworkElement的
,你不知道的这一种元素它是。这是因为你如何删除子取决于类型是很重要的。如果父是按钮
,那么你只清除内容
属性。如果父是画布
,你必须使用 Children.Remove
。
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
.
在一般情况下,你可以通过检查处理最常见的情况下,该项目是否为面板
,然后从它的孩子取出,否则,如果它是一个 ContentControl中
(如窗口
),然后将其内容
属性空
。但这并不是万无一失;还有其他的情况。
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.
您也必须小心,不要删除的东西是从模板扩大,因为这不是一个静态的内容,你可以修改的意愿。如果添加的控制或存在于静态的XAML中,你可以放心地将其删除。
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.