如何在TextBlock中显示更改时间?

时间:2011-02-13 16:27:43

标签: c# silverlight textblock stopwatch

所以我有一个秒表,我想要的就是它显示在一个文本块上。我怎么能这样做?

3 个答案:

答案 0 :(得分: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通知的基本思路是关键。

答案 1 :(得分:1)

TimerTextBlock用于显示TextBlock中的已用时间,并更新每秒后经过的时间。我认为你必须修改它作为秒表。

答案 2 :(得分:0)

Stopwatch用于两个时间点之间的测量。它不会发出任何可能驱动绑定的事件。您需要在模型中使用某种Timer(该链接假定WPF ...其他选项可用...更新您的标记)来创建更改通知。

相关问题