2011-05-03 38 views
4

我有一個WPF應用程序,在其中點擊一個菜單項,打開一個窗口。現在,如果在窗口已經打開時再次單擊相同的菜單項,它將打開一個新窗口,但我不希望每次都打開一個新窗口。 我需要的是,如果窗口已經打開,那麼同一個窗口應該關注的不是一個新窗口。如何停止每次打開新窗口?

在此先感謝。

回答

3

如果你打開的窗口被用作簡單的對話框,你可以用下面的代碼

window.ShowDialog(); 

時,對話框會顯示你不能按你關閉此窗口的任何菜單項單元

+0

如果你有一個TrayIcon有上下文菜單? – crypted 2013-05-25 08:32:36

1

您可以創建一個現場,並檢查它的設置:

private Window _dialogue = null; 
private void MaekWindowButton_Click(object sender, RoutedEventArgs e) 
{ 
    if (_dialogue == null) 
    { 
     Dialogue diag = new Dialogue(); 
     _dialogue = diag; 

     diag.Closed += (s,_) => _dialogue = null; //Resets the field on close. 
     diag.Show(); 
    } 
    else 
    { 
     _dialogue.Activate(); //Focuses window if it exists. 
    } 
} 
+0

非常感謝您的回覆。但我有另一個問題。實際上,我有不止一個這樣的窗口(如搜索窗口,比較窗口等),此代碼會發生什麼情況,一次只打開一個窗口。我希望每個這樣的窗口的一個實例應該被允許,但不是任何窗口的多個實例。 – 2011-05-04 06:28:36

+0

然後,爲每種類型的窗口創建一個字段。 – 2011-05-04 07:22:32

+0

yup ...我做了同樣的事情....再次感謝 – 2011-05-04 10:06:53

2

這樣一個相當強力方法也適用:

 bool winTest = false; 

     foreach (Window w in Application.Current.Windows) 
     { 
      if (w is testWindow) 
      { 
       winTest = true; 
       w.Activate(); 
      } 
     } 

     if (!winTest) 
     { 
      testWindow tw = new testWindow(); 
      tw.Show(); 
     } 
3
//First we must create a object of type the new window we want the open. 
NewWindowClass newWindow; 

private void OpenNewWindow() { 
    //Check if the window wasn't created yet 
    if (newWindow == null) 
    { 
     //Instantiate the object and call the Open() method 
     newWindow= new NewWindowClass(); 
     newWindow.Show(); 
     //Add a event handler to set null our window object when it will be closed 
     newWindow.Closed += new EventHandler(newWindow_Closed); 
    } 
    //If the window was created and your window isn't active 
    //we call the method Activate to call the specific window to front 
    else if (newWindow != null && !newWindow.IsActive) 
    { 
     newWindow.Activate(); 
    } 
} 
void newWindow_Closed(object sender, EventArgs e) 
{ 
    newWindow = null; 
} 

我認爲這解決了您的問題。

Att,

+1

極好的例子。解決了我的頭痛。 – 2013-09-04 02:57:07