Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a WPF window separately

Tags:

c#

wpf

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 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?

like image 276
What'sUP Avatar asked Mar 19 '11 15:03

What'sUP


People also ask

How do I close a window in WPF?

Pressing ALT + F4 . Pressing the Close button.

How do I close windows Mvvm?

<local:ViewModel/> </Window. DataContext> <StackPanel>

How do I close a window?

If you want to close the active window, you can also click Close Current Window on the File menu or press CTRL+F4.

Is WPF front end or backend?

WPF, stands for Windows Presentation Foundation is a development framework and a sub-system of . NET Framework. WPF is used to build Windows client applications that run on Windows operating system. WPF uses XAML as its frontend language and C# as its backend languages.


1 Answers

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.

like image 128
HCL Avatar answered Oct 01 '22 23:10

HCL