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

MagB picture MagB · Jul 11, 2014 · Viewed 8.5k times · Source

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#.

Answer

123 456 789 0 picture 123 456 789 0 · Jul 11, 2014

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.