Detect whether CanClose called because of activation of different screen or application exit

Sep 8, 2010 at 7:44 PM

In my Caliburn Micro based application, I have a ScreenConductor and a number of Screens.  In one of them, I want to prevent the user switching to a different scene dependent upon a certain criteria.  However, I've just managed to lock myself out of the ability to close the application as my CanClose now won't let me deactivate this screen when closing the application if the criteria evaluates to false.  For example:

public override void CanClose(Action<bool> callback)
    base.CanClose(result =>
        if (!result) callback(false);
        if (myObj == null ) result = false;

This is on a screen that is used to instantiate myObj and the other screens of the application depend upon myObj's existence, hence me wanting to prevent closure if myObj == null.  However if myObj is null, the user can't quit the app.  Can I somehow detect that CanClose is being called as part of an application closure rather than activation of a different screen?

If not, my alternative approach is to have the buttons used to switch to those other screens guarded with a method that checks for myObj != null and remove the CanClose.  Ideally I'd like to implement both options to prevent other methods of switching being accidentally implemented by my stupidity.

Thanks as always for any input!

Sep 8, 2010 at 8:02 PM

There's nothing out of the box for this. However, you could probably implement that pretty easy. Hook to the closing events for the main Window, app, whatever. Then use event agg to send a message indicating that is happening or set a global flag...something like that. You can then use that bit of information inside your CanClose method to determine the result.

Sep 9, 2010 at 9:15 AM

Ah, yes.  Wood/trees.  Thanks again, Rob.