背景;
自定义控件 usercontrol, 在 WrapPanel 显示。方式:
tWrapPanel.Children.Add(y);
问题:
父容器中加载了很多 usercontrol,当usercontrol 使用完了,点击usercontrol上的关闭按钮,关闭 usercontrol 控件,但是不关闭 父容器。
思路:
1、在usercontrol 中获得当前自定义控件的父容器;
2、删除父容器中 当前的usercontrol
ControlsEquiryHelp c = new ControlsEquiryHelp();
WrapPanel w = c.GetParentObject<WrapPanel>(this.Hvc_Y8000SerialControl, "");
w.Children.Remove(this.usercontrol的Name);
ControlsEquiryHelp类
(参考:: https://www.cnblogs.com/Seek-logic/p/3234008.html)
/// <summary>
/// 获取父控件
/// 调用方法:Grid layoutGrid = VTHelper.GetParentObject<Grid>(this.spDemoPanel, "LayoutRoot");
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="name"></param>
/// <returns></returns>
public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
{
DependencyObject parent = VisualTreeHelper.GetParent(obj);
while (parent != null)
{
if (parent is T && (((T)parent).Name == name || string.IsNullOrEmpty(name)))
{
return (T)parent;
}
parent = VisualTreeHelper.GetParent(parent);
}
return null;
}
///
/// 如果关闭 usercontrol 时,把对应的父容器也关闭,则使用下面方法:
///参考:https://blog.csdn.net/m0_37591671/article/details/79519298
///
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr GetParent(IntPtr hWnd);
//I'd double check this constant, just in case
static uint WM_CLOSE = 0x10;
private void CloseContainingWindow(Visual visual)
{
// Find the containing HWND for the Visual in question
HwndSource wpfHandle = PresentationSource.FromVisual(this) as HwndSource;
if (wpfHandle == null)
{
throw new Exception("Could not find Window handle");
}
// Trace up the window chain, to find the ultimate parent
IntPtr hWindow = wpfHandle.Handle;
while (true)
{
IntPtr parentHWindow = GetParent(hWindow);
if (parentHWindow == (IntPtr)0) break;
hWindow = parentHWindow;
}
// Now send the containing window a close message
SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
调用:
CloseContainingWindow(usercontrol);