正在捕捉窗口的返回

本文关键字:返回 窗口 | 更新日期: 2023-09-27 18:29:34

有一个函数可以打开并显示一个新窗口。我想对那扇窗户的关闭提出一个条件。我在下面写了我想要的伪代码。

private void fnc (object sender, RoutedEventArgs e)
{
    MyWindow nw = new MyWindow();
    nw.Show();
    // Pseudo code: When (nw.Close()) {do something}
}

正在捕捉窗口的返回

private void fnc (object sender, RoutedEventArgs e)
{
    MyWindow nw = new MyWindow();
    nw.Show();
    // inline
    nw.Closed += (s1, e1) => Debug.WriteLine("Closed");
    // or
    nw.Closed += (s1, e1) =>
                        {
                            Debug.WriteLine("Closed");
                        };
    // or
    w.Closed += OnWindowClosed;
}
private void OnWindowClosed(object s, EventArgs e)
{
    Debug.WriteLine("Closed");
}

您想要使用ShowDialog()。这将使您的代码等待,直到新窗口返回。

private void fnc (object sender, RoutedEventArgs e)
{
    MyWindow nw = new MyWindow();
    nw.ShowDialog();
    //Do something when nw returns
}

或者,如果你不想冻结你的父窗口,那么你必须连接到窗口。关闭

private void fnc (object sender, RoutedEventArgs e)
{
    MyWindow nw = new MyWindow();
    nw.Closed += nw_Closed;
    nw.Show();
}
private void new_Closed(object sender, CancelEventArgs e)
{
    //Do Something
}

如果您还没有准备好方法,也可以使用lambda表达式使用内联委托:

private void fnc (object sender, RoutedEventArgs e)
{
    MyWindow nw = new MyWindow();
    nw.Closed += (sender, cancelEventArgs) => 
        {
           //Do Something
        };
    nw.Show();
}