使窗口成为唯一的实例

时间:2015-11-16 20:47:27

标签: c# wpf

嘿我想确保我只能打开这个窗口的一个实例,它似乎不起作用而且不确定原因。

我检查已经打开了一个同名的窗口,并确保我没有检测到当前窗口是否正在尝试打开。

public new void Show()
{
    //Ensure new notifications are placed above older ones
    foreach (Window window in System.Windows.Application.Current.Windows)
    {
        string windowName = window.GetType().Name;
        if (!windowName.Equals("NotificationAll") && window != this)
        {
            this.Topmost = true;
            base.Show();

            this.Owner = System.Windows.Application.Current.MainWindow;

            //Position the Notification
            var workingArea = SystemParameters.WorkArea;
            this.Left = (workingArea.Width - this.ActualWidth) / 2;
            this.Top = workingArea.Bottom - this.ActualHeight;
        }
    }            
}

然而,不止一个窗口仍在打开!

2 个答案:

答案 0 :(得分:1)

要检查,如果没有其他Window具有相同名称,您可以使用此Linq声明:

if (!Application.Current.Windows.Cast<Window>().Where(x => 
    x != this).Any(x => x.GetType().Name == "NotificationAll"))
{

}

答案 1 :(得分:1)

您没有对之前打开的窗户做任何事情。试试这个修改:

public new void Show()
{
    //Ensure new notifications are placed above older ones
    foreach (Window window in System.Windows.Application.Current.Windows)
    {
        string windowName = window.GetType().Name;
        //ALSO CHECK BY PLACING BREAKPOINT AT THIS if TO SEE WHAT WINDOW
        //NAME ARE YOU GETTING OR IF YOU ARE ENTRING THIS BLOCK
        if (windowName.Equals("NotificationAll") && window != this)
        {
           //IF YOU WANT TO CLOSE PREVIOUS WINDOWS
           window.Close();
        }
     }

      //NOW MANIPLUATE CURRENT WINDOW'S PROPERTIES AND SHOW IT
      this.Topmost = true;
      base.Show();
       ....
       ....
       this.Top = workingArea.Bottom - this.ActualHeight;
}

如果要关闭当前窗口并显示上一个窗口:

public new void Show()
{
    var hasOtherWindow=false;
    //Ensure new notifications are placed above older ones
    foreach (Window window in System.Windows.Application.Current.Windows)
    {
        string windowName = window.GetType().Name;
        if (!windowName.Equals("NotificationAll") && window != this)
        {
            hasOtherWindow=true;
            window.Topmost = true;
            //Position the Notification
            var workingArea = SystemParameters.WorkArea;
            window.Left = (workingArea.Width - window.ActualWidth) / 2;
            window.Top = workingArea.Bottom - window.ActualHeight;
            break;//GET OUT OF LOOP YOU WILL HAVE ONLY ONE WINDOW
        }
    }
    if(hasOtherWindow)
    Close();//CLOSE THIS WINDOW
}