我想制作一个简单的倒计时应用程序,使用C#语言作为示例。
对于第一个和基本版本,我使用一个标签来显示剩余时间(以秒为单位),并使用一个按钮来启动倒计时。按钮的点击事件实现如下:
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 60;
while (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
System.Threading.Thread.Sleep(1000);
}
}
现在,当用户点击按钮时,实际上会倒计时(因为应用程序冻结(由于Sleep()))选择的时间量,但标签的内容没有刷新。
我是否做错了什么(当涉及到线程时)或者这只是UI的问题?
谢谢你们的答案! 我现在使用System.Windows.Threading.DispatcherTimer按照您告诉我的方式操作。一切都运作良好,所以这个问题已经得到了解答 ;)
对于那些感兴趣的人:这是我的代码(基本部分)
public partial class WindowCountdown : Window
{
private int _time;
private DispatcherTimer _countdownTimer;
public WindowCountdown()
{
InitializeComponent();
_countdownTimer = new DispatcherTimer();
_countdownTimer.Interval = new TimeSpan(0,0,1);
_countdownTimer.Tick += new EventHandler(CountdownTimerStep);
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_time = 10;
_countdownTimer.Start();
}
private void CountdownTimerStep(object sender, EventArgs e)
{
if (_time > 0)
{
_time--;
this.labelTime.Content = _time + "s";
}
else
_countdownTimer.Stop();
}
}