Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - How do I know if a WPF window is opened

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...