【问题标题】:How to stop a new window to be opened every time?如何停止每次打开一个新窗口?
【发布时间】:2011-05-03 11:07:17
【问题描述】:

我有一个 WPF 应用程序,单击菜单项会打开一个窗口。如果在窗口已经打开时再次单击相同的菜单项,它正在打开一个新窗口,但我不希望每次都打开一个新窗口。

我需要的是,如果窗口已经打开,则应该关注同一个窗口而不是新窗口。

【问题讨论】:

    标签: wpf window


    【解决方案1】:
    //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;
    }
    

    我认为这可以解决您的问题。

    态度,

    【讨论】:

    • 很好的例子。解决了我的头痛。
    【解决方案2】:

    如果您打开的窗口用作简单对话框,您可以使用以下代码

    window.ShowDialog();
    

    当对话框显示你不能按任何菜单项时你关闭这个窗口

    【讨论】:

    • 如果您有一个带有上下文菜单的 TrayIcon 怎么办??
    【解决方案3】:

    这样的蛮力方法也有效:

            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();
            }
    

    【讨论】:

      【解决方案4】:

      您可以创建一个字段并检查它是否已设置:

      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.
          }
      }
      

      【讨论】:

      • 非常感谢您的回复。但我还有另一个问题。实际上我有多个这样的窗口(如搜索窗口、比较窗口等),这段代码会发生什么,在一次只打开一个窗口。我希望每个这样的窗口都有一个实例,但不允许任何窗口的多个实例。
      • 然后为每种类型的窗口创建一个字段。
      • 不客气,如果这充分回答了您的问题,您可以通过单击左侧的复选标记大纲来标记它。
      猜你喜欢
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多