Create a Countdown Timer in Silverlight
I want to have a counter that counts down from 60 seconds to 0. I want the user to see the number of seconds on the UI. To accomplish this, I thought I would display a basic TextBlock like 开发者_C百科such:
<StackPanel>
<TextBlock Text=" " />
<TextBlock Text=" seconds remaining" />
</StackPanel>
I then was thinking of using a Timer. The only timer I'm aware of though is the DispatcherTimer. However, that doesn't show how much time has elapsed or how much time is remaining. Because of this, I have nothing to bind to.
private DispatcherTimer myTimer = new DispatcherTimer();
public MainPage() {
myTimer.Interval = new TimeSpan(0, 0, 60);
myTimer.Tick += new EventHandler(myTimer_Tick);
myTimer.Start();
}
I'm not sure how to do this. A co-worker told me that I shouldn't even do this because it will slow down the UI. But the users really want it. Can somebody tell me:
1) Will it really bog down the UI that much? 2) If not, how do I do this?
Thanks!
Yes. It will slow it down by an imperceivable amount. Frankly, it would be absolutely ridiculous to be worried about this.
On every tick, decrement a property. Bind your UI to that property. Alternatively, simply invalidate a property on every tick, and have the property getter calculate the time remaining.
Option 1
myTimer.Interval = TimeSpan.FromSeconds(1);
myTimer.Tick += delegate
{
this.SecondsRemaining = this.SecondsRemaining - 1;
if (this.SecondsRemaining == 0)
{
myTimer.Dispose();
}
};
this.SecondsRemaining = 60;
myTimer.Start();
...
// assumes your class implements INotifyPropertyChanged and you have a helper method to raise OnPropertyChanged
public int SecondsRemaining
{
get { return this.secondsRemaining; }
private set
{
this.secondsRemaining = value;
this.OnPropertyChanged(() => this.SecondsRemaining);
}
}
Option 2
myTimer.Interval = TimeSpan.FromSeconds(1);
myTimer.Tick += delegate
{
this.OnPropertyChanged("TimeRemaining");
if (this.TimeRemaining <= 0)
{
myTimer.Dispose();
}
};
this.endTime = DateTime.UtcNow.AddMinutes(1);
myTimer.Start();
public int TimeRemaining
{
get { return (endTime - DateTime.UtcNow).TotalSeconds; }
}
No it should not bog the UI down since it will be firing every second; sample on how to do this can be found here.
In addition you could also use a Storyboard which runs for your specified time frame and adjusts a UI component accordingly however I would not recommended that approach.
精彩评论