How to check if ANY ContentDialog is open?
Asked Answered
U

3

7

So we can only have one opened content dialog at a time. This is fine. But in my app there are several possible content dialogs that can be opened, and I would like to avoid making my own variable because I can forget to add it somewhere and the whole app will crash (because trying to open second content dialog throws exception).

So my question is: How to check if any ContentDialog is open?

Note:

  1. I don't want to check for specific ContentDialog.
  2. I would like to avoid creating my own variables.
Unfeeling answered 1/1, 2019 at 14:4 Comment(0)
T
16

ContentDialog is shown in the PopupRoot so using VisualTreeHelper.GetOpenPopups() will help you get it.

var openedpopups = VisualTreeHelper.GetOpenPopups(Window.Current);
foreach (var popup in openedpopups)
{
   if(popup.Child is ContentDialog)
   {
      //some content dialog is open.
   }
}
Trifoliate answered 1/1, 2019 at 19:6 Comment(0)
K
5

Tested accepted answer (by Vignesh) on target Windows 10 build 18362 and find that ContentDialog is never a child of popup. In my case simple check of the count works best:

    protected bool IsAnyContentDialogOpen()
    {
        return VisualTreeHelper.GetOpenPopups(Window.Current).Count > 0;
    }

Please feel free to comment if there's any problems with this approach. Thanks.

Kevyn answered 6/4, 2020 at 23:12 Comment(1)
This returns true when a MenuFlyout is opened.Islas
C
0

I used Linq to make this process a bit easier:

using System.Linq;

var dialog = 
    VisualTreeHelper.GetOpenPopups(Window.Current)
    .Where(p => p.Child is ContentDialog)
    .FirstOrDefault();
if (dialog != null)
{
    // A dialog is open
}
else
{
    // Show my dialog
}
Cartel answered 4/12, 2023 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.