C# 启动新窗口时如何关闭当前窗口(在代码中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19248822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:30:58  来源:igfitidea点击:

How to close current window (in Code) when launching new Window

c#wpfxaml

提问by software is fun

SignInWindow signIn= new SignInWindow();
signIn.ShowDialog();

The above code is in my MainWindow class.

上面的代码在我的 MainWindow 类中。

When the new Window is shown, I want the current window to close. Whats the best way to do this?

显示新窗口时,我希望关闭当前窗口。什么是最好的方法来做到这一点?

My application is a C# WPF application

我的应用程序是一个 C# WPF 应用程序



I've tries this but when it's called, my application exits

我试过了,但是当它被调用时,我的应用程序退出

    static private void CloseAllWindows()
    {
        for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
            App.Current.Windows[intCounter].Close();
    }

采纳答案by Mike Perrenoud

Just do this:

只需这样做:

this.Close();
SignInWindow signIn = new SignInWindow();
signIn.ShowDialog();

bear in mind that will actually closethe MainWindow. If all you're reallytrying to do is hide it, then do this:

请记住,实际上会关闭MainWindow。如果您真正想做的只是隐藏它,请执行以下操作:

this.Hide();
SignInWindow signIn = new SignInWindow();
signIn.ShowDialog();
this.Show();

That will hidethe MainWindowwhile the login form is up, but then showit again when it's complete.

这将隐藏MainWindow,而登录表单,但后来表明它再次它完成时。



Okay, so apparently you're launching this form from a static classthat is outsidethe form. That would have been pretty relevant information. But a solution would be this:

好了,显然你推出从这种形式static class外面的形式。那将是非常相关的信息。但一个解决方案是这样的:

var w = Application.Current.Windows[0];
w.Hide();

SignInWindow signIn = new SignInWindow();
signIn.ShowDialog();

w.Show();

回答by DJ Dev J

You can try this:

你可以试试这个:

SignInWindow signIn= new SignInWindow();
Application.Current.Windows[0].Close();
signIn.ShowDialog();

回答by Maalu...

This is a kind of redirection code. it will close current window/page and redirect to the new page/window in wpf

这是一种重定向代码。它将关闭当前窗口/页面并重定向到 wpf 中的新页面/窗口

SignWindow sw = new SignWindow();
this.Content = sw;

回答by Ketan Dubey

Mike Perrenoud's answer is 100% perfect, although you might want to create a object of the new window and activate it, before you close the Main Window.

Mike Perrenoud 的回答是 100% 完美的,尽管您可能希望在关闭主窗口之前创建新窗口的对象并激活它。