-5

I want to close a window in WPF after clicking a button that sends me to another window.

I tried with win3.Close(); but it doesn't work. This is the Main Window that references to the second window.

private void Button_Click_1(object sender, RoutedEventArgs e)
 {
   Window2 win3 = new Window2();
   win3.Show();
 }

Or it should be hidden?

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Nomonom
  • 137
  • 2
  • 11
  • 3
    Where you want to close the Window? is it in same button click? – sujith karivelil Jan 07 '16 at 09:23
  • If you hide it, it'll still be there, using resources, etc. - just hidden. – Wai Ha Lee Jan 07 '16 at 09:24
  • Have a look at this question. Hope it be what you want: http://stackoverflow.com/questions/33281524/hidden-form-not-closing – Salah Akbari Jan 07 '16 at 09:24
  • If you think about it: Win1 has the Reference to Win2, so would you like to close Win1 so it looses the Reference to Win2? If you do not want to go back to Win1, you have to elevate the Window Handling to an WindowContainer. If you want to go back to Win1, you should just hide and re-show it. – Matthias Müller Jan 07 '16 at 09:26

3 Answers3

-1

You can use this.Close(), this will close WPF window as like winform.close();

But in your case you can use this code:

Window wpfForm = Application.Current.Windows.OfType<Window>().SingleOrDefault(win => win.Name == "YourNameOfWindow");
wpfForm.Close();
rdn87
  • 739
  • 5
  • 18
-1

You only need to input this.Close(); before showing next window.

private void Button_Click_1(object sender, RoutedEventArgs e)

 {
   Window2 win3 = new Window2();
   this.Close();
   win3.Show();
 }
Ben sin aspa
  • 100
  • 11
-2

you could use

Application.Current.Windows[1].Close();
GrayFox
  • 997
  • 1
  • 9
  • 26