如何阻止从wpf应用程序打开多个窗口?
我需要从菜单中打开一个窗口,如果我再次打开它,我希望已经打开的窗口变为活动状态。
有什么建议吗?
答案 0 :(得分:5)
您可以使用Application.Current.Windows
集合。只需检查此集合是否包含您要打开的窗口,如果是,请激活它,否则创建新窗口并显示它:
var existingWindow = Application.Current.Windows.Cast<Window>().SingleOrDefault(w => /* return "true" if 'w' is the window your are about to open */);
if (existingWindow != null) {
existingWindow.Activate();
}
else {
// Create and show new window
}
答案 1 :(得分:2)
这是一种方法:
private Window _otherWindow;
private void OpenWindow()
{
if (_otherWindow == null)
{
//Pass in a reference to this window so OtherWindow can call WindowClosed when it is closed..
_otherWindow = new OtherWindow(this);
_otherWindow.Show();
}
else
_otherWindow.Activate(); //Or whatever the method is to bring a window to the front
}
public void WindowClosed()
{
_otherWindow = null;
}