【发布时间】:2020-08-10 21:05:27
【问题描述】:
所以我想从另一个线程中另一个类中的静态方法访问主窗体中的标签
我该怎么做?
顺便说一句,我用这段代码来启动线程
new Thread(new ThreadStart(WebHelper.Check)).Start();
【问题讨论】:
-
你不应该。移动数据,而不是控件。
标签: c# .net multithreading winforms
所以我想从另一个线程中另一个类中的静态方法访问主窗体中的标签
我该怎么做?
顺便说一句,我用这段代码来启动线程
new Thread(new ThreadStart(WebHelper.Check)).Start();
【问题讨论】:
标签: c# .net multithreading winforms
UI 只能由 UI 线程更改。如果您的线程与表单在同一个类中,您可以使用Control.Invoke 方法访问 UI 线程。
this.Invoke(new Action(() => {
//UI Code here
}));
但是,如果你想从另一个类访问它,我建议使用events 访问 UI 的类,然后你可以使用 Invoke。
//This would be in your class
public delegate void UIStuff(string text);
class AClass
{
public static event UIStuff ChangeLabel;
public static void StaticFunction() {
ChangeLabel.Invoke("Test");
}
}
//This would be your form class
public partial class Form1 : Form
{
public Form1(){
AClass.ChangeLabel += AClass_ChangeLabel; //Note you can press tab for auto complete
}
AClass_ChangeLabel(string text) {
this.Invoke(new Action(() => {
this.MainLabel = text;
}));
}
}
注意:我相信你也可以通过在静态方法Form1 f1 = new Form1(); 中创建一个新实例来更改标签,但我不相信这就是你想要的。
【讨论】: