我试图在按钮上异步更新计时器。
例如我设定时间= 60秒
当我在几个TIME之后运行程序时,计时器已经达到45秒,当我单击按钮时,它应该添加j = 15秒的时间,并且计时器应该异步更改为60秒。请帮忙
private int time = 60;
DateTime dt = new DateTime();
private j = 15 ;
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += timer_tick;
timer.Start();
}
void timer_tick(object sender, EventArgs e)
{
if (time >0)
{
time--;
text.Text = TimeSpan.FromSeconds(time).ToString();
}
else
{
timer.Stop();
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
text.Text = dt.AddSeconds(j).ToString("HH:mm:ss");
}
答案 0 :(得分:1)
以下是我的代码,您可以尝试使用它。
private int time = 60;
DateTime dt = new DateTime();
private int j = 15;
private Timer timer1 = new Timer();
void timer_tick(object sender, EventArgs e)
{
if (time > 0)
{
time--;
text.Text = TimeSpan.FromSeconds(time).ToString();
}
else
{
timer1.Stop();
}
}
public timer()
{
InitializeComponent();
timer1 = new Timer();
timer1.Interval = 1000;
timer1.Tick += timer_tick;
timer1.Start();
}
private void button1_Click(object sender, EventArgs e)
{
time += j;
}