Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何阻止每次打开新窗口?_Wpf_Window - Fatal编程技术网

Wpf 如何阻止每次打开新窗口?

Wpf 如何阻止每次打开新窗口?,wpf,window,Wpf,Window,我有一个WPF应用程序,在其中,单击菜单项就会打开一个窗口。如果在窗口已打开时再次单击同一菜单项,则会打开一个新窗口,但我不希望每次都打开一个新窗口 我需要的是,如果窗口已打开,则应将同一窗口作为焦点,而不是新窗口。如果将打开的窗口用作简单对话框,则可以使用以下代码 window.ShowDialog(); 当对话框显示您不能按任何菜单项时,关闭此窗口您可以创建一个字段并检查它是否已设置: private Window _dialogue = null; private void MaekWi

我有一个WPF应用程序,在其中,单击菜单项就会打开一个窗口。如果在窗口已打开时再次单击同一菜单项,则会打开一个新窗口,但我不希望每次都打开一个新窗口


我需要的是,如果窗口已打开,则应将同一窗口作为焦点,而不是新窗口。

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

window.ShowDialog();

当对话框显示您不能按任何菜单项时,关闭此窗口

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

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

类似这样的蛮力方法也能奏效:

        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();
        }
我想这可以解决你的问题


Att,

非常感谢您的回复。但我有另一个问题。实际上,我有不止一个这样的窗口(如搜索窗口、比较窗口等),这段代码的作用是,一次只能打开一个窗口。我希望每个窗口都可以有一个实例,但任何窗口都不能有多个实例。只需为每种类型的窗口创建一个字段。不客气,如果这充分解决了您的问题,您可以通过单击左侧的复选框框来标记它。如果您有一个具有上下文菜单的TrayIcon呢?很好的示例。解决了我的头痛。
//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;
}