如何在 TextBlock 中显示更改时间? [英] How do I display changing time within a TextBlock?

查看:32
本文介绍了如何在 TextBlock 中显示更改时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a stopwatch and all I want is for it to be display on a textblock. How can I do that?

推荐答案

创建一个 TimerViewModel,看起来像这样:

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

然后像这样绑定:

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

就像一个魅力.我敢肯定,您需要稍微修改一下基本概念,但让 DispatcherTimer 触发 PropertyChanged 通知的基本想法是关键.

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.

这篇关于如何在 TextBlock 中显示更改时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆