我有一个打开窗口的按钮。
如果再次按下该按钮,则会打开同一窗口的副本。
info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
如何检查Window是否已打开,并拒绝重复打开?
我无法使用info.ShowDialog()
,因为它会停用Main Window
。
尚无效的解决方案:
Info info = new Info();
if (!info.IsActive)
{
info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
}
Info info = new Info();
if (info.Visibility != Visibility.Visible)
{
info.Owner = Window.GetWindow(this);
info.Show();
}
public static bool IsWindowOpen<T>(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType<T>().Any()
: Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
}
private void buttonInfo_Click(object sender, RoutedEventArgs e)
{
if (!IsWindowOpen<Window>("Info"))
{
Info info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
}
}
答案 0 :(得分:2)
明智的做法是只跟踪Window实例,这样您就不必在以后找到它。添加字段:
private Info infoWindow;
如果它为null,那么您知道该窗口尚未存在,因此您将要创建它。使用Closed事件将变量设置回null。如果它不为null,那么您要确保窗口恢复。所以:
private void button_Click(object sender, RoutedEventArgs e) {
if (infoWindow == null) {
infoWindow = new Info();
infoWindow.Closed += (s, ea) => infoWindow = null;
infoWindow.Owner = this; // optional
infoWindow.Show();
}
else {
if (infoWindow.WindowState == WindowState.Minimized) {
infoWindow.WindowState = WindowState.Normal;
}
infoWindow.Activate();
}
}
当包含按钮的窗口关闭时,您可能还想自动关闭窗口:
private void Window_Closed(object sender, EventArgs e) {
if (infoWindow != null) infoWindow.Close();
}
答案 1 :(得分:2)
仅当value不为null时才创建表单。 如果表单已关闭,则使用FormClosed事件将值返回null。
public static Info info;
if(info == null){
info = new Info();
info.Show();
}
在信息表单上放置一个事件表格
private void info_FormClosed(object sender, FormClosedEventArgs e)
{
MainForm1.info = null;
}
它对我有用
答案 2 :(得分:0)
您可以使用.IsLoaded
字段或绑定.ContentRendered
事件
窗口1:
public class Window1 : Window
{
private Info info = null;
private Boolean IsInfoOpened = false;
protected void OpenInfo()
{
if (this.IsInfoOpened) return;
this.info = new Info();
this.info.ContentRendered += delegate { this.IsInfoOpened = true; };
this.info.Closed += delegate { this.IsInfoOpened = false; }
this.info.Show();
}
}