Wpf closing all windows

Closing all Windows in a C# WPF application

I’m creating a little WPF app in VS2013Express and I’ve come across a little problem. You see, there are three windows, MainWindow , LatAndLongDialog , TimeCitiesDialog .

LatAndLongDialog and TimeCitiesDialog are opened from MainWindow (with the click of a button). I want all the other windows to close when the Closed() event is called on MainWindow . The code on MainWindow.xaml.cs:

How can I close ’em all? Please help!

4 Answers 4

The proper way to shutdown a WPF app is to use Application.Current.Shutdown() . This will close all open Window s, raise some events so that cleanup code can be run, and it can’t be canceled. Environment.Exit() terminates the application immediately even if other threads are executing.

You should also consider setting the Owner on non-main Window s. The behavior will likely be more like what you would expect in regards to Z-order, minimizing, and maximizing. As an added bonus, the owned windows will automatically close when the owner Window closes.

Close all opened current windows.

Use this instead this.Close()

this will force everything to close

If you keep track of the Dialogs outside of the scope of the methods you use to open them, you can call which ever methods on those Dialogs you wish from anywhere within the Class. Here I have them as Class variables and they are instantiated there but not shown until you press the buttons. You can also create «Close» buttons for those specific windows and call their .Close() methods when ever you wish. That will allow you to open and close them at will. You can also call their .Close() methods when the main form closes.

Not the answer you’re looking for? Browse other questions tagged c# .net wpf or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Closing all windows in WPF after one has been closed

Is there any way I could close all windows after the user closes one of them, and here is the important part: without using App.Current.Shutdown() , but rather by invoking close on remaining windows individually?

My idea was to just invoke close on each of the remaining windows in the Window_Closing event handler method. There’s one problem, though. Suppose I have two window classes, A and B . I create one instance of A and B — a and b respectively. If I close window A , then it invokes the Window_closing event handler method and calls b.close() there. Then in the B class ( A and B are window classes, they both inherit from Window ) Window_closing method is invoked (because I’ve just called B.close() ), and B::Window_closing calls a.close() and it results in exception cause I’ve already closed a .

What is the right way to solve this?

3 Answers 3

If you are interested in having a «main window» and «tool windows», so that closing the main window closes all of them and closing tool windows does, well, only just that — then in the App.xaml there’s a friendly option just for that!

Читайте также:  Рейтинг приложения для windows

Note that here, the «MainWindow» in question, is the main window the application starts with (or the one you set as main, if you played with that during the app’s lifetime).

EDIT: afterthought: That will of course close all the windows, but I’m not actually sure if it calls normal «Close», or just shutsdown the whole application. Sorry, you’d need to check it for yourself. If you’re interested in my opinion, that’s the way you should/could do that easily, and if you really-really-need to shutdown the app by «Close()»ing every window, then I sense you’re doing something wrong here, as if I remember correctly, «Window.Close()» may be cancelled.

EDIT2: yup, Window.Close() can be cancelled. Please see this article:

Closing a window causes the Closing event to be raised. If the Closing event isn’t canceled, the following occurs: (. )

So looping over the window collection and calling ‘Close’ doesn’t really guarantee that the windows will really be closed and the app may still be left running afterwards.

How do I exit a WPF application programmatically?

In the few years I’ve been using C# (Windows Forms), I’ve never used WPF. But, now I love WPF, but I don’t know how I am supposed to exit my application when the user clicks on the Exit menu item from the File menu.

Among many others. Nothing works.

16 Answers 16

To exit your application you can call

As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:

Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:

  • When ShutdownMode is set to OnLastWindowClose.
  • When the ShutdownMode is set to OnMainWindowClose.
  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.

Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

If you really need it to close out you can also use Environment.Exit(), but it is not graceful at all (more like ending the process).

Use it as follows:

As wuminqi said, Application.Current.Shutdown(); is irreversible, and I believe it is typically used to force an application to close at times such as when a user is logging off or shutting down Windows.

Instead, call this.close() in your main window. This is the same as pressing Alt + F4 or the close [x] button on the window. This will cause all other owned windows to close and will end up calling Application.Current.Shutdown(); so long as the close action wasn’t cancelled. Please see the MSDN documentation on Closing a Window.

Also, because this.close() is cancellable you can put in a save changes confirmation dialog in the closing event handler. Simply make an event handler for and change e.Cancel accordingly. (See the MSDN documentation for more details on how to do this.)

Use any of the following as needed:

1.

2.

Above all methods will call closing event of Window class and execution may stop at some point (cause usually applications put dialogues like ‘are you sure?’ or ‘Would you like to save data before closing?‘, before a window is closed completely)

3. But if you want to terminate the application without any warning immediately. Use below

This should do the trick:

If you’re interested, here’s some additional material that I found helpful:

Here’s how I do mine:

I only call for Application.Current.ShutDown() from the main application window, all other windows use this.Close() . In my main window, Window_Closing(. ) handles the top right x button. If any of the methods call for window closer, Window_Closing(. ) grabs the event for shut down if user confirms.

The reason I do in fact use Application.Current.Shutdown() in my main window is that I’ve noticed that if a design mistake was made and I haven’t declared a parent of one of my windows in an application, if that window is opened without being shown prior to the last active window closing, I’m left with a hidden window running in the background. The application will not shut down. The only way to prevent complete memory leak is for me to go into the Task Manager to shut down the application. Application.Current.Shutdown() protects me from unintended design flaws.

Читайте также:  Adobe after effects для линукс

That is from my personal experience. In the end, use what is best for your scenario. This is just another piece of information.

How to Close a Window in WPF on a escape key

I want to close the windows in my wpf project when the user clicks the escape button. I don’t want to write the code in every window but want to create a class which can catch the when the user press the escape key.

5 Answers 5

Option 1

When you set the IsCancel property of a button to true, you create a Button that is registered with the AccessKeyManager. The button is then activated when a user presses the ESC key.

However, this works properly only for Dialogs.

Option2

You add a handler to PreviewKeyDown on the window if you want to close windows on Esc press.

Here is a button-less solution that is clean and more MVVM-ish. Add the following XAML into your dialog/window:

and handle the event in the code-behind:

One line to put after InitializeComponent():

Please note that this kind of code behind does not break MVVM pattern since this is UI related and you don’t access any viewmodel data. The alternative is to use attached properties which will require more code.

You can create a custom DependencyProperty:

And use it your windows’ XAML like this:

The answer is based on the content of the gist referenced in this answer.

The InputBinding options here are nice and flexible.

If you want to use an event handler, be aware that the Preview events happen quite early. If you have a nested control that should take the Esc key for its own purposes, stealing it at the window level may brake that control’s functionality.

Instead you can handle the event at the window level only if nothing else wants to with:

Not the answer you’re looking for? Browse other questions tagged c# .net wpf xaml or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

WPF MVVM: How to close a window

I have a Button that closes my window when it’s clicked:

That’s fine until I add a Command to the Button i.e.

Now it doesn’t close presumably because I am handling the Command . I can fix this by putting an EventHandler in and calling this.Close() i.e.

but now I have code in my code behind i.e. the method SaveCommand . I am using the MVVM pattern and SaveCommand is the only code in my code behind.

How can I do this differently so as not to use code behind?

21 Answers 21

I just completed a blog post on this very topic. In a nutshell, add an Action property to your ViewModel with get and set accessors. Then define the Action from your View constructor. Finally, invoke your action in the bound command that should close the window.

In the ViewModel:

and in the View constructor:

Finally, in whatever bound command that should close the window, we can simply invoke

Читайте также:  История скайпа windows 10

This worked for me, seemed like a fairly elegant solution, and saved me a bunch of coding.

Very clean and MVVM way is to use InteractionTrigger and CallMethodAction defined in Microsoft.Interactivity.Core

You will need to add a new namespace as below

You will need the Microsoft.Xmal.Behaviours.Wpf assembly and then the below xaml code will work.

You don’t need any code behind or anything else and can also call any other method of Window .

As someone commented, the code I have posted is not MVVM friendly, how about the second solution?

1st, not MVVM solution (I will not delete this as a reference)

2nd, probably better solution: Using attached behaviours

Behaviour Class Something similar to this:

I’d personally use a behaviour to do this sort of thing:

You can then attach this to your Window and Button to do the work:

I’ve added Command and CommandParameter here so you can run a command before the Window closes.

For small apps, I use my own Application Controller for showing, closing and disposing windows and DataContexts. It’s a central point in UI of an application.

It’s something like this:

and their invocations from ViewModels:

Of course you can find some restrictions in my solution. Again: I use it for small projects, and it’s enough. If you’re interested, I can post full code here or somewhere else/

I’ve tried to resolve this issue in some generic, MVVM way, but I always find that I end up unnecessary complex logic. To achieve close behavior I have made an exception from the rule of no code behind and resorted to simply using good ol’ events in code behind:

Although I wish this would be better supported using commands/MVVM, I simply think that there is no simpler and more clear solution than using events.

I use the Publish Subscribe pattern for complicated class-dependencies:

ViewModel:

Window:

You can leverage Bizmonger.Patterns to get the MessageBus.

MessageBus

Subscription

There is a useful behavior for this task which doesn’t break MVVM, a Behavior, introduced with Expression Blend 3, to allow the View to hook into commands defined completely within the ViewModel.

This behavior demonstrates a simple technique for allowing the ViewModel to manage the closing events of the View in a Model-View-ViewModel application.

This allows you to hook up a behavior in your View (UserControl) which will provide control over the control’s Window, allowing the ViewModel to control whether the window can be closed via standard ICommands.

I struggled with this topic for some time, and eventually went with the simplest approach that is still consistent with MVVM: Have the button execute the Command that does all the heavy lifting and have the button’s Click handler close the window.

XAML

XAML.cs

SaveCommand.cs

True, there is still code-behind, but there isn’t anything inherently bad about that. And it makes the most sense to me, from an OO perspective, to just tell the window to close itself.

We have the name property in the .xaml definition:

Then we have the button:

Then in the ViewModel:

Then at last, the action method:

I used this code to close a pop-up window from an application..

I found myself having to do this on a WPF application based on .Net Core 3.0, where unfortunately behaviour support was not yet officially available in the Microsoft.Xaml.Behaviors.Wpf NuGet package.

Instead, I went with a solution that made use of the Façade design pattern.

Standard command property on the view model:

Because the Close() method is already implemented by the Window class, applying the façade interface to the window is the only required code behind in the UI layer (for this simple example). The command in the presentation layer avoids any dependencies on the view/UI layer as it has no idea what it is talking to when it calls the Close method on the façade.

Оцените статью