抓住窗户的回归

时间:2012-03-31 21:39:15

标签: c# wpf window

有一个功能,可以打开并显示一个新窗口。我想把一个条件放到那个窗口的闭包上。我在下面写了我想要的伪代码。

private void fnc (object sender, RoutedEventArgs e)
{
    MyWindow nw = new MyWindow();

    nw.Show();

    // Pseudo code: When (nw.Close()) {do something}
}

2 个答案:

答案 0 :(得分:4)

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");
}

答案 1 :(得分:1)

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

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

或者,如果您不想冻结父窗口,则必须附加到Window.Closed

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();
}