简体   繁体   中英

c# Application.Current.Windows does not include all windows

In an application, I need to open multiple popups but need to check if a popup already exists with a given reference (guid). If so, I will first close the existing popup and open a new one. I am using the below code but it looks like if my partial class variable Guid is reset each time a new popup is created and therefore the condition MRwin.GetGuid() == this.guid is always true. It is like if the guid variable was declared as static :-S Any idea?

public partial class MyPopup: MetroWindow 
{
  private Guid guid;

  public Guid GetGuid() 
  {
    return guid;
  }

  public MyPopup(Guid guid) 
  {
    InitializeComponent();
    this.guid = guid;

    foreach(var win in Application.Current.Windows) 
    {
      if (win is Forms.MyPopup) 
      {
        Forms.MyPopup cWin = (Forms.MyPopup) win;

        // Close if there is any open popup window related to the same Guid
        if (cWin.GetGuid() == this.guid) 
        {
          cWin.Close();
        }
      }
    }
  }
}

This is a bad job for the constructor. If you don't need to create a window, don't create it. Creating it and then closing it isn't reasonable. And it causes your issue, since your newly partially created window is already in the Application.Current.Windows list!

Instead of having this kind of logic in a constructor, use a static method (or a factory):

public static MyPopup OpenPopup(Guid guid) =>
  Application.Current.Windows
    .OfType<Forms.MyPopup>()
    .FirstOrDefault(w => w.GetGuid() == guid)
  ?? new MyPopup(guid);

(feel free to return null if you don't want to return a reference to an existing popup).

Finally, Application.Current.Windows did not include one of the opened windows certainly due to threading. To address the issue I decided create and maintain a list of opened windows using a static list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM