In a WPF window, how do I know if it is opened?
My goal to open only 1 instance of the window at the time.
So, my pseudo code in the parent window is:
<
In WPF
there is a collection of the open Windows
in the Application
class, you could make a helper method to check if the window is open.
Here is an example that will check if any Window
of a certain Type
or if a Window
with a certain name is open, or both.
public static bool IsWindowOpen(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType().Any()
: Application.Current.Windows.OfType().Any(w => w.Name.Equals(name));
}
Usage:
if (Helpers.IsWindowOpen("MyWindowName"))
{
// MyWindowName is open
}
if (Helpers.IsWindowOpen())
{
// There is a MyCustomWindowType window open
}
if (Helpers.IsWindowOpen("CustomWindowName"))
{
// There is a MyCustomWindowType window named CustomWindowName open
}