所以我有一个秒表,我想要的只是让它显示在一个文本块上。我怎样才能做到这一点?
问问题
2700 次
3 回答
4
创建一个 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 通知的基本概念才是关键。
于 2011-02-14T04:56:28.877 回答
1
TimerTextBlock用于在 TextBlock 中显示经过的时间,并在每一秒后更新经过的时间。我认为您将不得不对其进行修改以充当秒表。
于 2011-04-22T07:25:39.877 回答