开发者

Close a WPF window separately

Goal:

Enable closing of the application's window(s) independently without affecting others. The application is created in WPF.

Problem:

Can't close the window(s)

In winform, it is enough to have the code winform.close() to close down the window but it doesn't work in 开发者_JS百科WPF.

You can have this code to close a specfic window:

Application.Current.Windows[0].Close(); 

but how would it work if you have many windows and you want to close a specific window without affecting the others?


Use the Application class to get the windows through Application.Windows-property exactly as you described. If you are in the code-behind of the window, call this.Close();

Configuration for multiple Windows
Set the main window to the Application.MainWindow property and set the Application.ShutdownMode to a appropriate value if you also want to hold the app open, if the main window is closed (e.g App.Current.ShutdownMode=ShutdownMode.OnExplicitShutdown; ).

I have already observed, that some people have had problems with the ShutdownMode. A workaround for this is to open the first window invisible and from this window, you open the visible application windows. This prevents the application from closing if the first created window will be closed. However you should be able to resolve this problem also over the ShutdownMode-property.
In scenarios with multiple windows, you can use Shutdown to close the app without closing every window.

I hope this answer is what your question is about. Make a comment if not.


I am agree with HCL. You can use this.Close(); from code-behind of the window, this will close WPF window as like winform.close();.

Or you can use following code for get the specific window for close

Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == "Window Name");
win.Close();


just use this code to close the most recent window

Application.Current.Windows[Application.Current.Windows.Count - 1].Close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜