在Silverlight中创建倒数计时器

时间:2010-12-02 21:04:13

标签: c# silverlight

我希望计数器从60秒倒数到0.我希望用户看到UI上的秒数。为了实现这一点,我想我会显示一个基本的TextBlock:

<StackPanel>
  <TextBlock Text=" " />
  <TextBlock Text=" seconds remaining" />
</StackPanel>

然后我考虑使用Timer。我知道的唯一计时器是DispatcherTimer。但是,这并未显示已经过了多长时间或剩余多少时间。因此,我没有什么可以约束的。

private DispatcherTimer myTimer = new DispatcherTimer();    
public MainPage() {
  myTimer.Interval = new TimeSpan(0, 0, 60);
  myTimer.Tick += new EventHandler(myTimer_Tick);
  myTimer.Start();
}

我不知道该怎么做。一位同事告诉我,我甚至不应该这样做,因为它会减慢用户界面的速度。但是用户真的想要它。有人能告诉我:

1)它真的会让UI陷入困境吗? 2)如果没有,我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:3)

  1. 是。它会以不可思议的数量减慢速度。坦率地说,担心这件事是绝对荒谬的。

  2. 在每个刻度线上,减少一个属性。将UI绑定到该属性。或者,只需在每个刻度上使属性无效,并让属性getter计算剩余时间。

  3. 选项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);
        }
    }
    

    选项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; }
    }
    

答案 1 :(得分:1)

不,它不应该降低用户界面,因为它将每秒开火;关于如何执行此操作的示例可以找到here

此外,您还可以使用在指定时间范围内运行的Storyboard,并相应地调整UI组件,但我不建议采用这种方法。

相关问题