我有一个WPF应用程序,在该应用程序中,单击菜单项会打开一个窗口。如果在窗口打开时再次单击相同的菜单项,则会打开一个新窗口,但我不希望每次都打开一个新窗口。
我需要的是,如果窗口已经打开,则应该关注同一窗口而不是新窗口。
答案 0 :(得分:4)
//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 :(得分:3)
如果您打开的窗口用作简单对话框,则可以使用以下代码
window.ShowDialog();
当对话框显示您无法按任何菜单项单位时关闭此窗口
答案 2 :(得分: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 :(得分: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.
}
}