I am trying to have a label display the time it takes the user to complete a task which starts at 00:00:00 and goes up in shown millisecond increments from there.
So far I have this:
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(); is called on a button click
Can someone point me in the right direction?
I’d recommend taking an MVVM approach. Have your TextBlock bind to a string member on your ViewModel. In your ViewModel you can use a DispatcherTimer to set the the time elapsed. The DispatcherTimer fires its callback on the UI thread so you don’t need to invoke to the UI thread.
Code:
XAML: