【问题标题】:How to Close newWindow (if it is opened already) then Open that newWindow ? WPF如何关闭新窗口(如果它已经打开)然后打开那个新窗口? WPF
【发布时间】:2019-03-18 08:56:50
【问题描述】:

我想检查按钮单击事件(打开 newWindnow).. 如果 newWindow 已经打开,则应先将其关闭,然后再打开它。因为我每次都可以为该 newWindow 提供动态内容。 这是 Winform 应用程序中的代码,但我需要它用于 WPF

private void button_Click(object sender, EventArgs e)
{
using (Form fc= Application.OpenForms["newWindow"])
{
if (fc!=null){
fc.Close();
nw= new newWindow(Id, Ip, name);
}
else{
nw= new newWindow(Id, Ip, name);
}
}
nw.Show();
}

谢谢

【问题讨论】:

标签: c# .net wpf visual-studio


【解决方案1】:

只需查看Application.Current.Windows 而不是Application.OpenForms。 WPF 等效项是:

private void button_Click(object sender, RoutedEventArgs e)
{
    var fc = Application.Current.Windows.OfType<newWindow>().FirstOrDefault();
    if (fc != null)
    {
        fc.Close();
    }
    nw = new newWindow(Id, Ip, name);
    nw.Show();
}

【讨论】:

    【解决方案2】:

    How do I know if a WPF window is opened

    你可以像这样创建一个辅助方法:

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

    用法:

    if (Helpers.IsWindowOpen<Window>("MyWindowName"))
    {
       // MyWindowName is open
    }
    
    if (Helpers.IsWindowOpen<MyCustomWindowType>())
    {
        // There is a MyCustomWindowType window open
    }
    
    if (Helpers.IsWindowOpen<MyCustomWindowType>("CustomWindowName"))
    {
        // There is a MyCustomWindowType window named CustomWindowName open
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多