question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked BitSmithy-4663 commented

How to modify ContentDialog closing behavior

Hello,

I have ContentDialog with primary button and close button.
I want that when I press primary button the dialog doesnt be closed.
It should be closed only if close button was clicked.

Below my code:

     private async void btnSave_Click(object sender, RoutedEventArgs e)
     {

         ContentDialog saveDialog = new ContentDialog
         {
             CloseButtonText = "Cancel",

             IsPrimaryButtonEnabled = true,
             PrimaryButtonText = "Save",
         };

     ContentDialogResult result = await saveDialog.ShowAsync();

         if (result == ContentDialogResult.Primary)
         {
             I want run some code here, but does not close the ContentDialog
         }
         else
         {
            
         The ContentDialog should be closed
            
             // The user clicked the CLoseButton, pressed ESC, Gamepad B, or the system back button.
             // Do nothing.
         }
     }

Please write, how to code such task

windows-uwp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AryaDing-MSFT avatar image
0 Votes"
AryaDing-MSFT answered BitSmithy-4663 commented

Hi,

Welcome to Microsoft Q&A!

You could set a global variable named sign, then set args.Cancel in ContentDialog.Closing event through it. As follows:

 public bool sign;
 private void Dialog_CloseButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
    {
        sign = false;          
    }
    
 private void Dialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
    {
             sign = true;
            // Perform your action
     }
 private void Dialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args)
     {
            if (sign)
             {
                 args.Cancel = true;           
             }       
      }


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

But how to attach handlers:
- Dialog_CloseButtonClick
- Dialog_PrimaryButtonClick

to CloseButton and PrimaryButton?
I dont see such possibility.

0 Votes 0 ·

I found the solution

these functions must be attached to:

         saveDialog.CloseButtonClick += Dialog_CloseButtonClick;
         saveDialog.PrimaryButtonClick += Dialog_PrimaryButtonClick;
0 Votes 0 ·