我想将DateTime显示在表单“Form1”的文本框中。我创建了一个类“schedule”来创建一个间隔为1秒的计时器。但是无法访问和更新Form1的文本框字段“xdatetxt”。我无法理解为什么它不能访问Form1中的控件xdatetxt。
Schedule.cs
class Schedule{
System.Timers.Timer oTimer = null;
int interval = 1000;
public Form anytext_Form;
public Schedule(Form anytext_form)
{
this.anytext_Form = anytext_form;
}
public void Start()
{
oTimer = new System.Timers.Timer(interval);
oTimer.Enabled = true;
oTimer.AutoReset = true;
oTimer.Start();
oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
}
private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{//i want to put here a line like "anytext_Form.xdatetxt.Text = System.DateTime.Now.ToString();"
}
}
form1.cs中的:
public partial class Form1 : Form{
public Form1()
{
InitializeComponent();
InitializeScheduler();
}
void InitializeScheduler()
{
Schedule objschedule = new Schedule(this);
objschedule.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
答案 0 :(得分:0)
因此,您需要获取要修改文本的表单实例。您可以通过将引用传递给objschedule或使用Application.openforms
来完成。
如果您已经引用了表单,那么第一种方法就是完美的,但如果您没有,只需:
private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
dynamic f = System.Windows.Forms.Application.OpenForms["anytext_Form"];
f.xdatetxt.Text=System.DateTime.Now.ToString();
}
答案 1 :(得分:0)
检查此SO线程 - How to access Winform textbox control from another class?
基本上公开更新文本框
公开文本框
另请注意,您需要更新UI线程中的表单控件
答案 2 :(得分:0)
这里有一些问题,但两者都很容易解决。
问题1:通过基类引用表单
您的Schedule
课程'构造函数采用Form
的实例。这是您的Form1
类的基类,它没有xdatetxt
字段。更改您的Schedule
构造函数以接受并存储Form1
的实例:
public Form1 anytext_Form;
public Schedule(Form1 anytext_form)
{
this.anytext_Form = anytext_form;
}
问题2:从非UI线程更新控件
修复编译器错误后,您将遇到运行时错误。原因是Timer
类在后台线程上执行其回调。您的回调方法尝试从该后台线程访问UI控件,这是不允许的。
我可以在这里提供内联解决方案,但我会在另一篇StackOverflow帖子中指出您有关于该问题以及如何修复问题的详细信息:Cross-thread operation not valid。