如何从一个 Windows 窗体控件访问另一个 Windows 窗体控件?
假设我创建一个窗口表单 Form.cs
。它有一些控件(label1、label2、button1、button1 等)。我还在 Form.cs
下创建了一个新的窗口窗体 New_Form.cs
。现在我想访问 New_Form.cs
中的 label1、label2、button1。我该怎么做?
Suppose I create a window form Form.cs
. It has some controls(label1, label2, button1, button1 etc.). I also create a new window form New_Form.cs
under Form.cs
. Now I want to access label1, label2, button1 in New_Form.cs
. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不想冒犯,但我认为使用另一种形式的控件并不是一个好的设计。
在我看来,将一个类(在这个问题中
form1
)耦合到另一个类的内部实现(“form2”的控件)是不好的。如果你,对于某些原因,必须更改该类的内部设计(例如,使用不同的控件显示数据),这使得编码(当然还有错误搜索)变得非常困难。在两个类之间交换数据,我更喜欢使用在内部设计中,您可以将它们附加到控件,但这种“耦合”保留在同一个类中)
I don't want to be offensive, but I think that using control from another form is not a good design.
In my oppinion it is not good to couple one class (in this question
form1
) to the inner implementation of another class (controls of `form2´. If you, for some reason, have to change the inner design (e.g. showing the data with a different control) of that class, you have to change the other class too. That makes coding (and of course error searching) quite difficult.If there is a need to exchange data between two classes, I would prefer using publioc Properties for that. In the inner design you can attach them to a control, but then this "coupling" stays in the same class)
虽然这可能是糟糕的设计,但您可以通过将属性公开然后访问它们来访问另一个表单中的属性,如下所示:
此外,这里还有一个与您的问题相关的 msdn 页面
http://msdn.microsoft.com/en-us/library/f6525896%28v=vs.90%29.aspx
Although this can be bad design, you can access properties in another Form by making them public and then accessing them like this:
Also here is an msdn page pertaining to your question
http://msdn.microsoft.com/en-us/library/f6525896%28v=vs.90%29.aspx
您可以通过在
Parent
表单中将所需属性设置为公共属性来访问它们。不确定为什么您需要该按钮,如果您希望为单击执行某些操作,那么您应该将逻辑封装到单独的方法中,然后由它们进行调用。如果您需要传递的详细信息较少,则为新表单创建接受这些值的构造函数
或
You can access the required properties by setting them as public properties in your
Parent
form. Not sure as why you would want the button, if you want some thing to be executed for the click then you should encapsulate the logic into separate methods and them make the call.If you have fewer details to pass then make constructors for the new form which would accept those values
or