在 C# 中切换表单的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/741699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best method to switch between forms in C#?
提问by
What's the best method to switch between forms in C# ?
在 C# 中切换表单的最佳方法是什么?
Scenario: I want to click a button in a Form1, kill the existing Form1 and create Form2. How can I achieve this ?
场景:我想单击 Form1 中的一个按钮,杀死现有的 Form1 并创建 Form2。我怎样才能做到这一点?
I would much appreciate it, if someone could even compare the complexity of this task in Winforms vs WPF.
如果有人甚至可以比较 Winforms 与 WPF 中此任务的复杂性,我将不胜感激。
采纳答案by JaredPar
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.
WPF 的代码类似。最大的区别是 WPF 窗口(以及几乎所有的类)不实现 IDisposable,因此不需要 using 语句。
var win1 = new Window1();
win1.ShowDialog();
var win2 = new Window2();
win2.ShowDialog();
回答by Noldorin
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.
当然,关闭当前表单,创建新表单的实例并显示它只是一件非常简单的事情吗?以下代码(在您的案例中的 Click 事件处理程序下)应该在 WinForms 或 WPF 中工作。
this.Close();
(new Form2()).Show();
Am I missing something here perhaps?
我可能在这里错过了什么吗?