There is no StopWatch for Silverlight.
What would you use instead of it?
I saw some posts about people saying to create an empty animation and call GetCurrentTime() from the Storyboard class, I couldn't get it to work...
What would you do?
There is no StopWatch for Silverlight.
What would you use instead of it?
I saw some posts about people saying to create an empty animation and call GetCurrentTime() from the Storyboard class, I couldn't get it to work...
What would you do?
There's a few things you could do with this. The fist is use something like the Environment.TickCount like the person here. However, something that I think may work better is to make use of a DispatcherTimer.
To set up a DispatcherTimer to work like a stopwatch we'll also need an associated TimeSpan representing the time it is run. We can instantiate the DispatcherTimer and set the interval that it times, and the handler for the Tick event.
DispatcherTimer _timer;
TimeSpan _time;
public Page()
{
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
_timer.Tick += new EventHandler(OnTimerTick);
}
In the UI we can create something simple to start and stop our timer, as well as display the stopwatch data:
<StackPanel>
<Button Content="Start" x:Name="uiStart" Click="OnStartClick" />
<Button Content="Stop" x:Name="uiStop" Click="OnStopClick" />
<TextBlock x:Name="uiDisplay"/>
</StackPanel>
Now, all that is left is the event handlers.
The OnTimerTick handler will incrementing and display our stopwatch data.
Our Start handler will take care of initalizing/reinitalizing our TimeSpan, while the Stop handler will just stop the DispatcherTimer.
void OnTimerTick(object sender, EventArgs e)
{
_time = _time.Add(new TimeSpan(0, 0, 0, 0, 10));
display.Text = _time.ToString();
}
private void OnStartClick(object sender, RoutedEventArgs e)
{
_time = new TimeSpan(0,0,0,0,0);
_timer.Start();
}
private void OnStopClick(object sender, RoutedEventArgs e)
{
_timer.Stop();
}