【发布时间】:2011-02-13 16:27:43
【问题描述】:
所以我有一个秒表,我只想让它显示在文本块上。我该怎么做?
【问题讨论】:
-
我们是在说 WPF 还是 Silverlight,还是????
标签: c# silverlight textblock stopwatch
所以我有一个秒表,我只想让它显示在文本块上。我该怎么做?
【问题讨论】:
标签: c# silverlight textblock stopwatch
创建一个 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 通知的基本概念才是关键。
【讨论】:
TimerTextBlock 用于在 TextBlock 中显示经过的时间,并在每一秒后更新经过的时间。我认为您将不得不对其进行修改以充当秒表。
【讨论】: