Charles LAU
Charles LAU

Reputation: 281

Windows Close button in WPF

I am currently working on a WPF application with Caliburn framework. At the top right of the application windows, there is a windows CLOSE(X) button. I would like to catch the event for the windows CLOSE button. However, when the application window is closing, the fade out will begin regardless of any buttons which will close the application windows. Also, when the application closes, the application will ask the user whether they want to save the changes or not if there is any changes. However, I can only manage to get the EXIT button in my application to pop up the SAVE CHANGES message and then start the fade out, but this does not occur for the windows CLOSE(X) button. When I pressed the windows CLOSE(X) button, the fadeout will begin first*(Therotically, this shouldn't happen, it should show the SAVE CHANGES message first and then fadeout afterwards)*. During the fade out, the SAVE CHANGES message appears. At the end, the application crashes because the application cannot close as the message still shows in the application. Does any one know any way to work around this? Below is the code I used for the issue.

The code-behind of the wpf view - I used this to catch the event for WINDOWS CLOSE button:

 protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (!closed)
            {
                e.Cancel = true;
                FormFadeOut.Begin();
                closed = true;
            }
            base.OnClosing(e);
        }

This code is used to close the application when the fadeout ends:

private void FormFadeOutAnimation_Completed(object sender, EventArgs e) {

        this.Close();

}

In my xaml,I used this code in order to call the function to pop up the SAVE CHANGES message when it is closing:

cal:Message.Attach="[Event Closing] = [Action CloseApp2()]"

In my view model, the following function is called by the above xaml code:

  public void CloseApp2()
        {

          //  isClosing = true;
            events.Publish(new IsClosingEvent());
          //  events.Publish(new ClearItemsEvent());
          //  events.Publish(new SwitchTimerOffEvent());
          //  Thread.Sleep(2000);

        }

When the "IsClosingEvent" event is sent, the SAVE CHANGES message will appear if there are any changes made by the user.

Does anyone have any good idea of how to solve this issue?

Thanks for any helps in advance.

Charles

Upvotes: 1

Views: 5502

Answers (1)

Thiru kumaran
Thiru kumaran

Reputation: 1342

Use Window.Closing event instead of

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)

Upvotes: 2

Related Questions