在wpf中有一个自定义用户控件,其中有一个按钮,内容为X。当这个控件的按钮被外界点击时,会在父控件中删除这个按钮
时间: 2024-01-22 17:21:29 浏览: 16
实现这个功能,你需要在自定义用户控件中订阅按钮的 Click 事件,然后在事件处理程序中通过 VisualTreeHelper 找到父控件并将按钮从其子元素集合中移除。
具体代码如下:
```csharp
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
MyButton.Click += MyButton_Click;
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
// 找到父控件
DependencyObject parent = VisualTreeHelper.GetParent(this);
while (parent.GetType() != typeof(ParentControl))
{
parent = VisualTreeHelper.GetParent(parent);
}
// 从父控件中移除按钮
((ParentControl)parent).Children.Remove(MyButton);
}
}
```
其中,`ParentControl` 是你所需要找到的父控件的类型,`MyButton` 是你要删除的按钮。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)