[英]Access and modify form listbox from another class
I'm having some issues accessing and modifying a listbox control from another class. 我在从另一个类访问和修改列表框控件时遇到一些问题。
Here's the MainForm, which holds the listbox: 这是MainForm,其中包含列表框:
public partial class MainForm : Form
{
private static MainForm mainForm = new MainForm();
internal static MainForm init()
{
return MainForm.mainForm;
}
public MainForm()
{
InitializeComponent();
}
}
And here's the second class that I'm using to attempt to modify the listbox (the items are added from an event): 这是我用来尝试修改列表框的第二个类(项目是从事件中添加的):
public class Utils
{
void ItemsReceived(object sender, DataReceivedEventArgs<ListboxItems> e)
{
MainForm.init().listBox1.Items.Add("test");
}
}
Using this code setup, nothing is added to the listbox. 使用此代码设置,不会将任何内容添加到列表框中。 Any ideas? 有任何想法吗? Or even a better way to tackle this? 甚至是解决这个问题的更好方法?
Typically visual studio generates the following code in a Program.cs
file: 通常,Visual Studio在Program.cs
文件中生成以下代码:
Application.Run(new MainForm());
If this line still exists, your static mainForm
variable will hold a different instance of MainForm
than the one visible when running the application. 如果这一行仍然存在,则您的静态mainForm
变量将拥有与运行应用程序时可见的MainForm
实例不同的MainForm
实例。 If I'm right, change the line in Program.cs
to: 如果我是对的,请将Program.cs
的行更改为:
Application.Run(MainForm.init());
On a side note, while using the singleton (anti)pattern, consider changing the name of that method to GetInstance()
because init()
appears to initialize something. 附带说明一下,在使用单例(反)模式时,请考虑将该方法的名称更改为GetInstance()
因为init()
似乎在初始化某些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.