0

I want to make check on button click event (which Opens newWindnow).. If newWindow already opened it should close it first, and then open it.. As I can have dynamic Content for that newWindow everytime.. Here is code in Winform Application, But I need it for 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();
}

Thanks

Mr. Xek
  • 81
  • 3
  • 12
  • 1
    Possible duplicate of [WPF version of Application.OpenForms](https://stackoverflow.com/questions/2877094/wpf-version-of-application-openforms) – Rekshino Mar 18 '19 at 09:37

2 Answers2

1

Just look in Application.Current.Windows instead of Application.OpenForms. The WPF equivalent would be:

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();
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

How do I know if a WPF window is opened

You can create a helper method like this:

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

Usage:

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
}
AmRo
  • 833
  • 1
  • 8
  • 19