我有以下类:C#WPF类属性标记
class MyTimer
{
class MyTimerInvalidType : SystemException
{
}
class MyTimerNegativeCycles : SystemException
{
}
private Timer timer = new Timer(1000);
private int cycles = 0;
public int Cycle
{
get
{
return this.cycles;
}
set
{
if(value >= 0)
this.cycles = value;
else
throw new MyTimerNegativeCycles();
}
}
private void timer_Tick(object sender, ElapsedEventArgs e)
{
try
{
this.Cycle--;
}
catch
{
this.Cycle = 0;
timer.Stop();
}
}
public MyTimer()
{
this.Cycle = 20;
timer.Elapsed += new ElapsedEventHandler(timer_Tick);
timer.Start();
}
}
在我的主窗口类我有一个列表我一个MyTimer添加当按下按钮:
private List<MyTimer> timers = new List<MyTimer>();
private void testbtn_Click(object sender, RoutedEventArgs e)
{
timers.Add(new MyTimer());
}
我试着将一个标签作为参考传递给MyTimer类并更新它,但这不起作用(无法从另一个线程访问UI元素)。
什么是在标签中显示MyTimer.Cycle的好方法,以便每次更改值时都会更新?
我必须能够将每个MyTimer“绑定”到代码中的不同标签(或者根本不将它绑定到标签)。
你是什么意思与“传递一个标签到'MyTimer'类”? –
@ nico-schertler我向MyTimer提供了一个方法,它将一个标签ref作为参数,然后试图通过它将一个ref传递给一个标签。 – Kyto