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#.
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.
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.
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:
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With