How do I display changing time within a TextBlock?

[亡魂溺海] 提交于 2019-12-06 15:50:40

Create a TimerViewModel, that looks something like this:

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));
        }
    }
}

Instantiate it like so in your code-behind:

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

    private TimerViewModel timerViewModel;
}

And then bind it like this:

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

Works like a charm. You'll need to modify the basic concept a bit I'm sure, but the basic idea of having a DispatcherTimer fire the PropertyChanged notification is what's key.

The TimerTextBlock is used to display the elapsed time in a TextBlock and updates the time elapsed after every second. I think you will have to modify it to act as a stop watch.

A Stopwatch is used for measurement between two points in time. It does not emit any kind of event that might drive a binding. You need to use some sort of Timer (the link assumes WPF... other options are available... update your tags) in your model to create change notifications.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!