如何使 UserControl 在运行时自行删除(在 WPF 中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13741349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:30:49  来源:igfitidea点击:

How to make a UserControl remove itself at runtime (in WPF)?

wpfuser-controlsdispose

提问by Ali

I have made a userControlconsisting a few labels and checkboxes and an "x" button for removing itself when clicked.

我制作了一个userControl由几个标签和复选框以及一个“x”按钮组成的按钮,用于在单击时自行删除。

Considering that in my WPF application, the user can dynamically put as many of this userControlat runtime as he wants, ANDthat none of them will have a nameattribute to address to, how exactly is it possible to remove a UserControlfrom the application, by clicking on it's -child- button "x" (i.e. inside the event handler of it's "x" button) ???

考虑到在我的 WPF 应用程序中,用户可以根据需要userControl在运行时动态放置尽可能多的这些,并且它们都没有name要寻址的属性,如何UserControl从应用程序中删除 a ,通过单击它是 -child- 按钮“x”(即在它的“x”按钮的事件处理程序中)???



I've already looked a thousand places and found these particular two lines of code which DID'NT WORK:

我已经看了一千个地方,发现这两行代码没有用

((Grid)button.Parent).Children.Remove(this);
((Button)control.Parent).Content = null;

回答by Clemens

In case your control has been added to any kind of container control (i.e. a class derived from Panel) the following should work:

如果您的控件已添加到任何类型的容器控件(即从 Panel 派生的类),则以下内容应该起作用:

((Panel)this.Parent).Children.Remove(this);