Hide all visible Metro Dialogs before showing anot

2019-04-01 00:58发布

问题:

I'm using MahApps.Metro on my WPF project, and I am building a class to help me showing Dialogs. I would like to know if there's a way of closing all visible dialogs before showing up another one.

Sometimes, when I show a ProgressDialog and then a MessageDialog the ProgressDialog isn't correctly closed, and stays in the background, so when I close the MessageDialog, it stays there freezing the UI.

Here's how I'm currently trying to hide all Dialogs:

public static async void HideVisibleDialogs(MetroWindow parent)
{
    BaseMetroDialog dialogBeingShow = await parent.GetCurrentDialogAsync<BaseMetroDialog>();

    while (dialogBeingShow != null)
    {
        await parent.HideMetroDialogAsync(dialogBeingShow);
        dialogBeingShow = await parent.GetCurrentDialogAsync<BaseMetroDialog>();
    }
}

I call it like this:

public static MessageDialogResult ShowMessage(String title, String message, MetroWindow parent, Int32 timeout, MessageDialogStyle style, MetroDialogSettings settings, MessageDialogResult defaultResult)
{
    AutoResetEvent arEvent = new AutoResetEvent(false);

    App.Current.Dispatcher.Invoke(() =>
    {
        HideVisibleDialogs(parent);
        arEvent.Set();
    });

    arEvent.WaitOne();

    [Rest of method]
}

Any help is appreciated. Thank you!

@EDIT

Apparently, the problem seems to be solved, thanks to Thomas Freudenberg

This is how it is now:

public static Task HideVisibleDialogs(MetroWindow parent)
{
    return Task.Run(async () => 
    {
        await parent.Dispatcher.Invoke(async () =>
        {
            BaseMetroDialog dialogBeingShow = await parent.GetCurrentDialogAsync<BaseMetroDialog>();

            while (dialogBeingShow != null)
            {
                await parent.HideMetroDialogAsync(dialogBeingShow);
                dialogBeingShow = await parent.GetCurrentDialogAsync<BaseMetroDialog>();
            }
        });
    });      
}

And I call it like this:

HideVisibleDialogs(parent).Wait();

回答1:

HideVisibleDialogs is an async method. I'd try to change its return type to Task and wait for it, i.e. HideVisibleDialogs(parent).Wait(). Otherwise the call would immediately return.