我试图让一个标签显示用户完成一项任务所花费的时间,该任务从 00:00:00 开始,并从那里以显示的毫秒增量上升。 到目前为止我有这个:
private void startTimer()
{
stopWatch.Start();
Dispatcher.BeginInvoke(DispatcherPriority.Render, new ThreadStart(ShowElapsedTime));
}
void ShowElapsedTime()
{
TimeSpan ts = stopWatch.Elapsed;
lblTime.Text = String.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
}
startTimer();
在按钮点击时被调用
有人能指出我正确的方向吗?
最佳答案
我建议采用 MVVM 方法。让您的 TextBlock 绑定(bind)到 ViewModel 上的字符串成员。在您的 ViewModel 中,您可以使用 DispatcherTimer 来设置耗时。 DispatcherTimer 在 UI 线程上触发其回调,因此您无需调用 UI 线程。
代码:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string TimeElapsed {get;set;}
private DispatcherTimer timer;
private Stopwatch stopWatch;
public void StartTimer()
{
timer = new DispatcherTimer();
timer.Tick += dispatcherTimerTick_;
timer.Interval = new TimeSpan(0,0,0,0,1);
stopWatch = new Stopwatch();
stopWatch.Start();
timer.Start();
}
private void dispatcherTimerTick_(object sender, EventArgs e)
{
TimeElapsed = stopWatch.Elapsed.TotalMilliseconds; // Format as you wish
PropertyChanged(this, new PropertyChangedEventArgs("TimeElapsed"));
}
}
XAML:
<TextBlock Text="{Binding TimeElapsed}"/>
关于c# - 在标签中显示部分程序的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10220528/