“Only a single ContentDialog can be open at any time.” error while opening another contentdialog

前端 未结 6 1455
半阙折子戏
半阙折子戏 2020-12-04 00:29

I am using Windows.UI.Xaml.Controls.ContentDialog to show a confirmation. And based on the response from the first dialog I would (or would not) show another di

6条回答
  •  猫巷女王i
    2020-12-04 01:07

    William Bradley's approach above is good. Just to polish it up a bit, here is an extension method to submit and await the showing of a content dialog; the dialog will be shown after all the other content dialogs that have already been submitted. Note: by the time the user clicks through earlier backlogged dialogs you may no longer want to show the dialog that you have submitted; to indicate this you may pass a predicate that will be tested after the other dialogs have been dismissed.

    static public class ContentDialogExtensions
    {
        static public async Task EnqueueAndShowIfAsync( this ContentDialog contentDialog, Func predicate = null)
        {
            TaskCompletionSource currentDialogCompletion = new TaskCompletionSource();
            TaskCompletionSource previousDialogCompletion = null;
    
            // No locking needed since we are always on the UI thread.
            if (!CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess) { throw new NotSupportedException("Can only show dialog from UI thread."); }
            previousDialogCompletion = ContentDialogExtensions.PreviousDialogCompletion;
            ContentDialogExtensions.PreviousDialogCompletion = currentDialogCompletion;
    
            if (previousDialogCompletion != null) {
                await previousDialogCompletion.Task;
            }
            var whichButtonWasPressed = ContentDialogResult.None;
            if (predicate == null || predicate()) {
                whichButtonWasPressed = await contentDialog.ShowAsync();
            }
            currentDialogCompletion.SetResult(null);
            return whichButtonWasPressed;
        }
    
        static private TaskCompletionSource PreviousDialogCompletion = null;
    }
    

    Another way might be to use a SemaphoreSlim(1,1).

提交回复
热议问题