Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if a WPF window is opened

Tags:

c#

window

wpf

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:

if (this.m_myWindow != null) {     if (this.m_myWindow.ISOPENED) return; }  this.m_myWindow = new MyWindow(); this.m_myWindow.Show(); 

EDIT:

I found a solution that solves my initial problem. window.ShowDialog();

It blocks the user from opening any other window, just like a modal popup. Using this command, it is not necessary to check if the window is already open.

like image 328
guilhermecgs Avatar asked Apr 24 '13 21:04

guilhermecgs


People also ask

How do I display a WPF window?

When a Window is created at run-time using the Window object, it is not visible by default. To make it visible, we can use Show or ShowDialog method. Show method of Window class is responsible for displaying a window.

Will WPF be discontinued?

It may indeed get phased out eventually “The WPF's goal in user interface and graphics rendering in the . NET Framework 3.0 release is to provide a windowing system for the desktop environment on Microsoft Windows.

What is the difference between WPF window and WPF page?

Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications.


1 Answers

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 } 
like image 150
sa_ddam213 Avatar answered Sep 20 '22 08:09

sa_ddam213