[英]I can't reach my current instance to change a label
I want to change a label text from my function class in the main form.我想在主窗体中从我的 function class 更改 label 文本。 I think I was able to narrow down the problem, but I can't find a good solution.
我想我能够缩小问题的范围,但我找不到好的解决方案。 Maybe I misunderstood the instances in WinForms.
也许我误解了 WinForms 中的实例。
Favorite solution Form 1最喜欢的解决方案 Form 1
public static Form1 f1Instance;
public Label lbl;
public Form1()
{
InitializeComponent();
f1Instance = this;
lbl = label1; //label1 = made by designer
}
Class 1 (can the problem be that i put my functions in a class and not a winform?) Class 1(问题是我将我的函数放在 class 而不是 winform 中吗?)
public void changeLblTxt(string txt)
{
Form1.f1Instance.lbl.Text = txt;
}
But that didn't work and I don't understand why.但这没有用,我不明白为什么。 Doesn't that call the currently displayed instance of Form1?
那不是调用了当前显示的Form1实例吗?
Solution that works Form 1适用于 Form 1 的解决方案
public static Form1 f1Instance;
public Label lbl;
public Form1()
{
InitializeComponent();
f1Instance = this;
lbl = label1; //label1 = made by designer
}
Class 1 Class 1
public void changeLblTxt(string txt)
{
Form1.f1Instance.lbl.Text = "Hello";
Form1.f1Instance.Show();
}
But I use it to call Form1 multiple times, don't I?但是我用它多次调用 Form1,不是吗? That wouldn't go well with a longer runtime and more interactions, would it?
go 运行时间更长,交互更多,这不是很好吗?
I have found countless articles on this subject but none have been able to help.我找到了无数关于这个主题的文章,但没有一篇能够提供帮助。 Does anyone know of an article that shows a good solution?
有谁知道一篇文章显示了一个很好的解决方案?
If you have a class that interacts with the form, then that class should have a reference to the form instance.如果您有一个与表单交互的 class,那么该 class 应该具有对表单实例的引用。 Using static fields and lists to try and get the "current" form instance seems like a poor design.
使用 static 字段和列表来尝试获取“当前”表单实例似乎是一个糟糕的设计。
I would just hand the class the form instance:我只会将表单实例交给 class:
class Class1 {
private Form1 form1;
public Class1(Form1 form1) {
this.form1 = form1;
}
// other stuff
}
Form1 frm = new Form1();
Class1 cls1 = new Class1(frm);
cls1.changeLblTxt("Test");
And similarly if you have two forms:同样,如果您有两个 forms:
class Form2: Form {
private Form1 form1;
public Form2(Form1 form1) {
this.form1 = form1;
}
// other stuff
}
Form1 frm1 = new Form1();
Form2 frm2 = new Form2(frm1);
fmr2.someMethod("Test");
After chatting with chatgpt i found a way: Form1与chatgpt聊天后,我找到了一种方法:Form1
public static List<Form1> formList = new List<Form1>();
public FormSettings()
{
InitializeComponent();
formList.Add(this);
}
Form2表格二
public void someMethod()
{
Form1 f1 = Form1.formList[0];
fs.SetLabelText(lines[i]);
}
Can someone explain to me why the list works but assigning it directly (first try to solve it) didn't work?有人可以向我解释为什么该列表有效但直接分配它(首先尝试解决它)不起作用吗? As far as I know, I did the same thing.
据我所知,我也做过同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.