我有一个Razor组件,用于启动计时器的按钮和一个计数器。问题是仅在按下按钮时才更新计数器。如何使每个滴答计时器更新计数器?
@page "/counter"
@using System.Threading;
@using System;
<h1>Counter</h1>
<p>Current : @currentCount</p>
<p>@TimerWorks</p>
<button class="btn btn-primary" @onclick="@StartTimer">Start the
Timer!</button>
@code {
int currentCount = 0;
string TimerWorks = "Disabled";
Timer timer;
void StartTimer()
{
if (timer == null)
{
timer = new Timer(_ => OnTime(this, null), null, 0, 1000);
TimerWorks = "Enabled";
}
else
{
TimerWorks = "Timer already works!";
}
}
void OnTime(object sender, EventArgs e)
{
currentCount++;
}
}