在表单之间共享父变量 [英] sharing parent variable between forms
问题描述
表单A打开表单B,表单A.visible = false;
form A opens form B, and form A.visible = false;
表单 A 有一个公共 int 变量,我需要表单 B 中的控件才能访问和修改此变量.是否可以这样做,因为通过构造函数传递值只是一种方法!
form A has a public int variable and I need controls in form B to be able to access and modify this variable. could this be done as passing the value through the constructor is only one way!
所以如果可以做到,如果表单 A 不可见,是否仍然可以访问该值?
and so if it could be done, if form A is not visible could the value still be accessed?
(表单 b 不应该是对话框!)
(form b is not supposed to be dialog!)
非常感谢!
我实际上不太明白解释.到目前为止是这样的:
edited: I do not quite get the explanations actually. so far it is like that:
形式a:
//in global space
public int temp = 123;
//in form_load event
Form setup = new setup();
setup.Show();
this.Visible = false;
在表单设置中:
//in form_load event
textBox1.text = temp.toString();
//in button_press event
form a.temp = "456";
我希望我已经清楚地解释了我的立场!
I hope I have explained my stance clearly!
推荐答案
首先,在表单A类型的表单B中拥有成员字段:
First, have member field in form B of type form A:
private FormA parent;
其次,在表单 B 中有这样的构造函数:
Second, have such constructor in form B:
public FormB(FormA parent)
: this()
{
this.parent = parent;
}
现在,当您创建表单 B 的实例时,将引用传递给正在运行的表单 A 实例:
Now when you create instance of form B, pass reference to the running form A instance:
FormB formB = new FormB(this);
formB.Show();
并且您可以通过 parent
字段访问公共属性,例如
And you can access the public property through the parent
field e.g.
//inside Form B code..
public Foo()
{
parent.PUblicProp = "Hello";
}
这篇关于在表单之间共享父变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!