c# - 在标签中显示部分程序的运行时间

标签 c# wpf

我试图让一个标签显示用户完成一项任务所花费的时间,该任务从 00:00:00 开始,并从那里以显示的毫秒增量上升。 到目前为止我有这个:

    private void startTimer()
    {
        stopWatch.Start();
        Dispatcher.BeginInvoke(DispatcherPriority.Render, new ThreadStart(ShowElapsedTime));
    }
    void ShowElapsedTime()
    {
        TimeSpan ts = stopWatch.Elapsed;
        lblTime.Text = String.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
    }

startTimer(); 在按钮点击时被调用

有人能指出我正确的方向吗?

最佳答案

我建议采用 MVVM 方法。让您的 TextBlock 绑定(bind)到 ViewModel 上的字符串成员。在您的 ViewModel 中,您可以使用 DispatcherTimer 来设置耗时。 DispatcherTimer 在 UI 线程上触发其回调,因此您无需调用 UI 线程。

代码:

public class ViewModel : INotifyPropertyChanged
{
     public event PropertyChangedEventHandler PropertyChanged;
     public string TimeElapsed {get;set;}

     private DispatcherTimer timer;
     private Stopwatch stopWatch;

     public void StartTimer()
     {
          timer = new DispatcherTimer();
          timer.Tick += dispatcherTimerTick_;
          timer.Interval = new TimeSpan(0,0,0,0,1);
          stopWatch = new Stopwatch();
          stopWatch.Start();
          timer.Start();
     }



     private void dispatcherTimerTick_(object sender, EventArgs e)
     {
         TimeElapsed = stopWatch.Elapsed.TotalMilliseconds; // Format as you wish
         PropertyChanged(this, new PropertyChangedEventArgs("TimeElapsed")); 
     }
}

XAML:

<TextBlock Text="{Binding TimeElapsed}"/>

关于c# - 在标签中显示部分程序的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10220528/

相关文章:

c# - 在 WPF 中以编程方式创建图像按钮

c# - 如何使用现有内容格式化 RichTextBox

c# - 折线的绑定(bind)。我究竟做错了什么?

c# - 带有 AccessText 的 wpf xaml 按钮似乎不查询 CanExecute

c# - 通过 LINQ 中的联结表将表连接在一起

c# - 如何为用户显示和隐藏 "Please wait"消息

c# - 防止控制台应用程序终止

javascript - 使用 jquery 发布数据时没有为此对象定义无参数构造函数

c# - 为什么 C# 将此类型推断为动态类型?

c# - 如何在 C# 中使用 XAML 中定义的画笔资源