Close the WPF window separately

Goal:
Enable closing application window (s) independently without affecting others. Application created in WPF.

Problem:

Unable to close window (s)

In winform, it is enough that winform.close() code closes the window, but it does not work in WPF.

You may have this code to close a special window:

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

but how will this work if you have many windows and want to close a specific window without affecting others?

+4
source share
3 answers

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

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

I already noticed that some people had problems with ShutdownMode. The workaround for this is to open the first invisible window, and from this window you will open the visible application windows. This prevents the application from closing if the first window created is closed. However, you must also solve this problem over the ShutdownMode property.
In multi-window scenarios, you can use Shutdown to close the application without closing each window.

Hope this answer will be your question. Make a comment if not.

+11
source

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

Or you can use the following code to get a specific window to close

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

just use this code to close the last window

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

Source: https://habr.com/ru/post/1344383/


All Articles