0

Is it possible to detect how a window is closed, when using Caliburn Micro? I.e. if it is closed via TryClose() or via the cross in the upper right corner of the window?

Based on this post I have found a way to catch the closing even, using the code below, but I cannot seem to find any property which indicates how the close was initiated?

public override void CanClose(Action<bool> callback) 
{
    // Only do this, if closed via the cross in the upper right corner of the window
    callback(false);
}
Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96

1 Answers1

0

I found a work around, which I think is quite simple. But strictly speaking it's not an answer to how to detect the method of closing. Still, it might be useful...

Step 1: Add a boolean somewhere in your view model (and make sure it is false by defaut)

public bool IsSubmitted { get; private set; } = false;

Step 2: Change the boolean value when submitting

public void SubmitForm() 
{
    IsSubmitted = true; // This is the only place this property will be changed
    // ...maybe do some more stuff?
    TryClose();
}

Step 3: Override the CanClose() method, also in the view model

public override void CanClose(Action<bool> callback) 
{
    if (IsSubmitted == false) 
    {
        callback(false); // Cancels the close
    }
}

You can also use the IsSubmitted after the close, which is why I made it public. As mentioned this does not directly detect the closing method, but it does allow me to detect if the form was actively submitted, which is good enough for my needs.

I would still love to see other answers, if there is a better way to do it :-)

Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96