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

前端 未结 6 1453
半阙折子戏
半阙折子戏 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条回答
  •  执念已碎
    2020-12-04 00:50

    I have created some code to handle this type of conundrum in my Apps:

    public static class ContentDialogMaker
    {
        public static async void CreateContentDialog(ContentDialog Dialog, bool awaitPreviousDialog) { await CreateDialog(Dialog, awaitPreviousDialog); }
        public static async Task CreateContentDialogAsync(ContentDialog Dialog, bool awaitPreviousDialog) { await CreateDialog(Dialog, awaitPreviousDialog); }
    
        static async Task CreateDialog(ContentDialog Dialog, bool awaitPreviousDialog)
        {
            if (ActiveDialog != null)
            {
                if (awaitPreviousDialog)
                {
                    await DialogAwaiter.Task;
                    DialogAwaiter = new TaskCompletionSource();
                }
                else ActiveDialog.Hide();
            }
            ActiveDialog = Dialog;
            ActiveDialog.Closed += ActiveDialog_Closed;
            await ActiveDialog.ShowAsync();
            ActiveDialog.Closed -= ActiveDialog_Closed;
        }
    
        public static ContentDialog ActiveDialog;
        static TaskCompletionSource DialogAwaiter = new TaskCompletionSource();
        private static void ActiveDialog_Closed(ContentDialog sender, ContentDialogClosedEventArgs args) { DialogAwaiter.SetResult(true); }
    }
    

    To use these Methods, you need to create the ContentDialog and its content in a variable, then pass the variable, and bool into the Method.

    Use CreateContentDialogAsync(), if you require a callback in your app code, say if you have a button in your Dialog, and you want wait for a button press, and then get the value from the form in code after the dialog.

    Use CreateContentDialog(), if you don't need to wait for the Dialog to complete in your UI Code.

    Use awaitPreviousDialog to wait for the previous dialog to complete before showing the next Dialog, or set false, to remove the previous Dialog, then show the next Dialog, say, if you want to show an Error Box, or the next Dialog is more important.

    Example:

    await ContentDialogMaker.CreateContentDialogAsync(new ContentDialog
    {
        Title = "Warning",
        Content = new TextBlock
        {
            Text = "Roaming Appdata Quota has been reached, if you are seeing this please let me know via feedback and bug reporting, this means that any further changes to data will not be synced across devices.",
            TextWrapping = TextWrapping.Wrap
        },
        PrimaryButtonText = "OK"
    }, awaitPreviousDialog: true);
    

提交回复
热议问题