[英]I can't reach my current instance to change a label
我想在主窗體中從我的 function class 更改 label 文本。 我想我能夠縮小問題的范圍,但我找不到好的解決方案。 也許我誤解了 WinForms 中的實例。
最喜歡的解決方案 Form 1
public static Form1 f1Instance;
public Label lbl;
public Form1()
{
InitializeComponent();
f1Instance = this;
lbl = label1; //label1 = made by designer
}
Class 1(問題是我將我的函數放在 class 而不是 winform 中嗎?)
public void changeLblTxt(string txt)
{
Form1.f1Instance.lbl.Text = txt;
}
但這沒有用,我不明白為什么。 那不是調用了當前顯示的Form1實例嗎?
適用於 Form 1 的解決方案
public static Form1 f1Instance;
public Label lbl;
public Form1()
{
InitializeComponent();
f1Instance = this;
lbl = label1; //label1 = made by designer
}
Class 1
public void changeLblTxt(string txt)
{
Form1.f1Instance.lbl.Text = "Hello";
Form1.f1Instance.Show();
}
但是我用它多次調用 Form1,不是嗎? go 運行時間更長,交互更多,這不是很好嗎?
我找到了無數關於這個主題的文章,但沒有一篇能夠提供幫助。 有誰知道一篇文章顯示了一個很好的解決方案?
如果您有一個與表單交互的 class,那么該 class 應該具有對表單實例的引用。 使用 static 字段和列表來嘗試獲取“當前”表單實例似乎是一個糟糕的設計。
我只會將表單實例交給 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");
同樣,如果您有兩個 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");
與chatgpt聊天后,我找到了一種方法:Form1
public static List<Form1> formList = new List<Form1>();
public FormSettings()
{
InitializeComponent();
formList.Add(this);
}
表格二
public void someMethod()
{
Form1 f1 = Form1.formList[0];
fs.SetLabelText(lines[i]);
}
有人可以向我解釋為什么該列表有效但直接分配它(首先嘗試解決它)不起作用嗎? 據我所知,我也做過同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.