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:
<Is that you search ?
if (this.m_myWindow != null)
{
if (this.m_myWindow.IsActive) return;
}
this.m_myWindow = new MyWindow();
this.m_myWindow.Show();
If you want a singleton, you should read this : How can we create a Singleton Instance for a Window?
If you need to activate the window if it is found, you can use the code below:
//activate a window found
//T = Window
Window wnd = Application.Current.Windows.OfType<T>().Where(w => w.Name.Equals(nome)).FirstOrDefault();
wnd.Activate();
Put a static bool in your class, named _open
or something like that.
In the constructor then do this:
if (_open)
{
throw new InvalidOperationException("Window already open");
}
_open = true;
and in the Closed event:
_open = false;
void pencereac<T> (int Ops) where T : Window , new()
{
if (!Application.Current.Windows.OfType<T>().Any()) // Check is Not Open, Open it.
{
var wind = new T();
switch (Ops)
{
case 1:
wind.ShowDialog();
break;
case 0:
wind.Show();
break;
}
}
else Application.Current.Windows.OfType<T>().First().Activate(); // Is Open Activate it.
}
Kullanımı:
void Button_1_Click(object sender, RoutedEventArgs e)
{
pencereac<YourWindow>(1);
}
You can check if m_myWindow==null
and only then create and show window. When the window closes set the variable back to null.
if (this.m_myWindow == null)
{
this.m_myWindow = new MyWindow();
this.m_myWindow.Closed += (sender, args) => this.m_myWindow = null;
this.m_myWindow.Show();
}
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<T>(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType<T>().Any()
: Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
}
Usage:
if (Helpers.IsWindowOpen<Window>("MyWindowName"))
{
// MyWindowName is open
}
if (Helpers.IsWindowOpen<MyCustomWindowType>())
{
// There is a MyCustomWindowType window open
}
if (Helpers.IsWindowOpen<MyCustomWindowType>("CustomWindowName"))
{
// There is a MyCustomWindowType window named CustomWindowName open
}