我有以下類: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