简体   繁体   中英

What's the best method to switch between forms in C#?

What's the best method to switch between forms in C# ?

Scenario: I want to click a button in a Form1, kill the existing Form1 and create Form2. How can I achieve this ?

I would much appreciate it, if someone could even compare the complexity of this task in Winforms vs WPF.

The easiest way to do this is to have a controlling function that opens both of the forms. When the button is clicked on the first form, close it and move onto the second form.

using (var form1 = new Form1() ) {
  form1.ShowDialog();
}
using (var form2 = new Form2()) {
  form2.ShowDialog();
}

The code for WPF is similar. The biggest difference is that WPF windows (and pretty much all classes as a rule) do not implement IDisposable and hence do not require the using statement.

var win1 = new Window1();
win1.ShowDialog();
var win2 = new Window2();
win2.ShowDialog();

Surely it's just a very straightforward matter of closing the current form, creating an instance of the new one, and showing it? The following code (under the Click event handler in your case) ought to work in WinForms or WPF.

this.Close();
(new Form2()).Show();

Am I missing something here perhaps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM