所以我有一个秒表,我只想将它显示在文本 block 上。我该怎么做?
创建一个 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;
}
然后像这样绑定(bind)它:
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding TimeFromStart}" />
</Grid>
像魅力一样工作。我敢肯定,您需要稍微修改基本概念,但让 DispatcherTimer 触发 PropertyChanged 通知的基本思想才是关键。
我是一名优秀的程序员,十分优秀!