对于访问另一个表单上的成员,Robert的回答是正确的。但是,一般来说,你应该保存你的应用程序的状态(称为“模型”),从用户界面的状态分别(称之为“视图”)。随着您的应用程序增长超过一个或两个交互,这变得非常重要。关于如何将两者结合在一起(例如Google的“模型 - 视图 - 控制器”(MVC)和“模型 - 视图 - 视图模型”(MVVM)),有几种哲学或模式,如果你真的想要正确地做到这一点,会推荐学习这些。我的首选是MVVM方法,即使它是在设计时考虑WPF应用程序,也可以使用Windows Forms轻松完成。
在.NET中,代码应该使用来实现您的视图模型和视图之间的连接基本片被称为INotifyPropertyChanged的接口。您创建一个实现了这个接口,并发送通知的类每当属性发生变化,因此,例如你的路径属性,你将创建这个类:
class ViewModel : INotifyPropertyChanged
{
private string path;
public string Path
{
get { return path; }
set {
if (value != path)
{
path = value;
NotifyPropertyChanged();
}
}
}
// This event gets triggered whenever a property changes.
public event PropertyChangedEventHandler PropertyChanged;
// This will cause the event to actually be triggered. It automatically determines the name of the property that triggered it using the [CallerMemberName] attribute - just a bit of .NET 4.5 sweetness. :)
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
它可能看起来像很多工作,但现在在你的Form1中您可以创建一个新的“ViewModel”实例,订阅该事件,然后将该实例传递给form2。然后,只要用户选择不同的路径,form2就更新视图模型实例上的Path属性。
所以,Form1中需要靠近顶部验证码:
private ViewModel viewmodel = new ViewModel();
而这正好在Form1构造函数:
viewmodel.PropertyChanged += new EventHandler(OnPathChanged);
而且当你创建/显示窗口2:
var form2 = new Form2(viewmodel); // Note, the viewmodel instance is being passed to the form2 constructor
form2.Show();
然后,form2构造函数将自己的引用存储到“viewmodel”实例中,并且每当th e路径被用户改变。
private ViewModel viewmodel;
public Form2(ViewModel viewmodel)
{
this.viewmodel = viewmodel;
... // Other stuff to set up your controls etc. goes here
}
private void PathChanged(object sender, EventArgs e) // This may be named differently in your code; it's the event handler that gets called when the path changes
{
// This will automatically notify the event handler in Form1! It's super-elegant and flexible.
this.viewmodel.Path = txtPath.Text; // Assuming you have a textbox called txtPath
}
最后事件处理程序在Form1中:
private void OnPathChanged(object sender, EventArgs e)
{
var newPath = viewmodel.Path; // Get the updated path back from the viewmodel
//TODO: Whatever you want to do when the path changes.
}
下面是使用Windows窗体一个非常好的MVVM介绍的链接,它采用两种形式就像你在你的例子都有。 MVVM (Model-View-ViewModel) Pattern For Windows Form Applications, using C#
一般来说,您将使用ShowDialog()显示Form2,然后在Form1中检查DialogResult.OK的结果(点击“OK”按钮时在Form2中将DialogResult设置为OK)。正如RobertHavey所解释的那样,您将使用Form2的引用来访问所需的值。缺少的成分是,您不能(默认情况下)访问存储在Form2上的TextBox中的值。您可以通过将TextBox的Modifiers()属性设置为Public来“解决”此问题。然而,首选的方法是在Form2上创建一个自定义属性来保存该值。 –
完美! DialogResult正是我所需要的。我忘记了窗户的回报。 –