Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing event fired twice when set the exitButton.IsCancel = True

Tags:

button

events

wpf

I realized when I set the exit button with attribute IsCancel = True, the Closing event of window will fire twice.

    private void exitButton_Click(object sender, RoutedEventArgs e)
    {
        // this button was set attribute IsCancel = True.
        Close();          
    }

    private void BaseWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {          
        MessageBox.Show("test"); // this message box will show twice
                                 // when you click on the exit button
        e.Cancel = true;
    }

Is this a bug of WPF ? Is there a workaround ?

Ps : Sorry I forgot to say this bug only occurs when you call your window from a parent window.

like image 977
JatSing Avatar asked Dec 02 '11 03:12

JatSing


1 Answers

I guess I don't see where this is unexpected behaviour.

If you designate this as the Cancel button and call .ShowDialog(), then clicking the button will close the window.

You've added your own call to Close() and canceled the close, so both calls are made and the event is raised both times.

update

In answer to your comment about why it might behave the way it does, the IsCancel and IsDefault properties provide an easy mechanism to define dialogs using XAML only. They save you the trouble of having to go into the codebehind to define boilerplate click handlers.

like image 157
Jay Avatar answered Sep 28 '22 06:09

Jay