显示标签中程序的一部分的运行时间

Noe*_*lle 2 c# wpf

我正在尝试让标签显示用户完成任务所需的时间.因此标签从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);
    }
Run Code Online (Sandbox Code Playgroud)

startTimer所(); 按下按钮调用

有人能指出我正确的方向吗?

Dan*_*sha 11

我建议采用MVVM方法.让TextBlock绑定到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")); 
     }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<TextBlock Text="{Binding TimeElapsed}"/>
Run Code Online (Sandbox Code Playgroud)

  • 不需要停止计时器吗?这不会永远运行吗? (2认同)