【问题标题】:How do I display changing time within a TextBlock?如何在 TextBlock 中显示更改时间?
【发布时间】:2011-02-13 16:27:43
【问题描述】:

所以我有一个秒表,我只想让它显示在文本块上。我该怎么做?

【问题讨论】:

  • 我们是在说 WPF 还是 Silverlight,还是????

标签: c# silverlight textblock stopwatch


【解决方案1】:

创建一个 TimerViewModel,如下所示:

public class TimerViewModel : INotifyPropertyChanged
{
    public TimerViewModel()
    {
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
        startTime = DateTime.Now;
    }

    private DispatcherTimer timer;
    private DateTime startTime;
    public event PropertyChangedEventHandler PropertyChanged;
    public TimeSpan TimeFromStart { get { return DateTime.Now - startTime; } }

    private void timer_Tick(object sender, EventArgs e)
    {
        RaisePropertyChanged("TimeFromStart");
    }

    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

在你的代码隐藏中实例化它:

public partial class TimerPage : UserControl
{
    public TimerPage()
    {
        InitializeComponent();
        timerViewModel = new TimerViewModel();
        DataContext = timerViewModel;
    }

    private TimerViewModel timerViewModel;
}

然后像这样绑定它:

<Grid x:Name="LayoutRoot" Background="White">
    <TextBlock Text="{Binding TimeFromStart}" />
</Grid>

像魅力一样工作。我敢肯定,您需要稍微修改基本概念,但让 DispatcherTimer 触发 PropertyChanged 通知的基本概念才是关键。

【讨论】:

    【解决方案2】:

    TimerTextBlock 用于在 TextBlock 中显示经过的时间,并在每一秒后更新经过的时间。我认为您将不得不对其进行修改以充当秒表。

    【讨论】:

      【解决方案3】:

      Stopwatch 用于两个时间点之间的测量。它不会发出任何可能驱动绑定的事件。您需要在模型中使用某种Timer(该链接假定为 WPF...其他选项可用...更新您的标签)来创建更改通知。

      【讨论】:

      • 基本上当他们按下一个按钮时秒表开始,当他们按下另一个按钮时秒表停止。但我想在文本块上向他们显示经过的时间。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多