在两个winform之间共享一个变量 [英] Sharing a variable between two winforms

查看:45
本文介绍了在两个winform之间共享一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 winforms 应用程序.

I have a winforms application.

我在一个表单上有一个文本框(调用 F1),当在这个表单上点击一个按钮(调用 F2)时,它会启动另一个表单.

I have a textbox on one form (call F1) and when a button is clicked on this form (call F2), it launches another form.

在 F2 上,我想通过文本框设置一个字符串(并将其保存到类中的一个变量中),然后当我关闭此表单时,该字符串将出现在 F1 的标签中.

On F2, I want to set a string via a textbox (and save it to a variable in the class), and then when I close this form, the string will appear in a label in F1.

所以我基本上是在两种形式之间共享变量.但是,我无法使其正常工作.这段代码看起来如何?

So I am basically sharing variables between both forms. However, I can't get this to work correctly. How would this code look?

推荐答案

我会向 form2 添加一个新属性.说它是一个电话号码.然后我将一个朋友属性 m_phone() 作为字符串添加到表单 2 中.在显示 form2 的一个实例之后但在关闭它之前,您可以在 form1 的代码中引用属性 m_phone.

I would add a new property to form2. Say it's for a phone number. Then I'd add a friend property m_phone() as string to form 2. After showing an instance of form2 but before closing it, you can refer to the property m_phone in form1's code.

这是 Matthew Abbott 解决方案的额外间接层.它不会将 form2 UI 控件暴露给 form1.

It's an additional level of indirection from Matthew Abbott's solution. It doesn't expose form2 UI controls to form1.

编辑

例如:

public string StoredText
{
    get;
    private set;
}

在 set 里面你可以引用你的 UI 控件,比如 return textBox1.text.使用 get 设置早期加载的文本框值.

inside the set you can refer to your UI control, like return textBox1.text. Use the get to set the textbox value from an earlier load.

还有:

public string GetSomeValue()
{
    var form = new F2();
    form.ShowDialog();

    return form.StoredText;
}

只需确保在关闭表单之前填充了 StoredText(或不填充,如果合适).

Just ensure that StoredText is populated (or not, if appropriate) before the form is closed.

这篇关于在两个winform之间共享一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆