如何使用 WPF 用户控件关闭父窗口 [英] How to close parent windows using WPF User Control

查看:59
本文介绍了如何使用 WPF 用户控件关闭父窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个 WPF 窗口:window_One 和 window_Two.

Assume that I have two WPF windows: window_One and window_Two.

  • window_One 有一个按钮.单击此按钮会打开 window_Two.
  • window_Two 包含一个用户控件.
    • 这个用户控件有一个按钮可以关闭 window_Two.

    我怎样才能实现这个场景?

    How can I achieve this scenario?

    推荐答案

    在您创建的自定义控件内部.您可以从按钮事件点击中访问父窗口.

    Inside the custom control that you've created. You can access the parent window from within the button event click.

    使用可视化树:

    var myWindow = (Window)VisualParent.GetSelfAndAncestors().FirstOrDefault(a => a is Window);
    myWindow.Close();
    

    或者简单地:

    var myWindow = Window.GetWindow(this);
    myWindow.Close();
    

    当然,另一种选择是创建一个显示MyButtonClicked"的自定义事件,然后让承载 UserControl 的窗口监听此事件,当事件被触发时,您关闭当前窗口.

    Of course, the other option would be to create a custom event that says "MyButtonClicked" and then have the window that hosts the UserControl to listen to this event and when the Event is fired, you close the current window.

    干杯!

    这篇关于如何使用 WPF 用户控件关闭父窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆