Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF + Caliburn Micro: how to catch Window Close event?

I am new in Caliburn Micro and learn it from this helloworld example. In the example there are only 2 views (.xaml) of type Application and UserControl, and 1 view model.

I avoid to use code behind. Therefore I have only view and view model. I want to know how to catch the window close event of my helloworld application so I can handle it in view model. My target: when user is going to close the app by pressing close [x] button on top-right corner the app gives feedback to the user.
I have read about IViewAware and IScreen, but I find no specific example related to my question.

A simple sample code for view and view model are highly appreciated. Thanks in advance.

PS. I use VS2013, C#.

like image 315
MagB Avatar asked Jul 11 '14 14:07

MagB


People also ask

How do I Close a window in WPF?

A Cancel button, typically on a modal dialog box. A Close button, typically on a modeless dialog box. Once a window is closed, the same object instance can't be used to reopen the window. For more information about the life of a window, see Overview of WPF windows: Window lifetime.

When is the closing event raised when closing a window?

The Closing event is raised when Close is called, if a window's Close button is clicked, or if the user presses ALT+F4. If an owned window was opened by its owner window using Show, and the owner window is closed, the owned window's Closing event is not raised.

Is it possible to subscribe to the main window closing event?

This option is even easier, and maybe is suitable for you. In your View Model constructor, you can subscribe the Main Window closing event like this:

How to handle closed and closing events in the view-model?

The code idea is to allow a Window's Closed and Closing events to be handled via commands in the View-Model, and to get this going I wrote an attached behavior for the Window object. Closed - This is executed when the Window.Closed event is fired. Execute - This is executed if the Window.Closing event was not cancelled.


Video Answer


2 Answers

What you can do is in your View you can attach Caliburn Micro by using

cal:Message.Attach="[Event Closing] = [Action OnClose($eventArgs)]"

So it will look like

<Window cal:Message.Attach="[Event Closing] = [Action OnClose($eventArgs)]">

And on your ViewModel you can just define a public method that says OnClose with CancelEventArgs as the parameter and you can handle it from there.

like image 103
123 456 789 0 Avatar answered Nov 15 '22 13:11

123 456 789 0


If your ViewModel inherits Screen, Caliburn Micro has some methods that you can override like

protected override void OnDeactivate(bool close); 

this is called when a screen is closed or deactivated or

public override void CanClose(Action<bool> callback)

you can check CanClose usage here

like image 36
gcores Avatar answered Nov 15 '22 13:11

gcores