WPF-计时器(自学记录)
用的wpf 为vs2017,应公司要求在采数时加入计时器,并一并保存下来。做个记录,主要为在WPF中,计时器的用法。
xaml中主要用到:textblock 和 textbox;<TextBlock Grid.Row="5" Grid.Column="4" HorizontalAlignment="Stretch" Margin="5" TextWrapping="Wrap" Text="计时器:" TextAlignment="Right" VerticalAlignment="Center" /> <TextBox x:Name="tb_timer" Grid.Row="5" Grid.Column="5" HorizontalAlignment="Stretch" Margin="1" TextAlignment="Center" VerticalAlignment="Center" Foreground="#FF307095"/>
添加完界面显示后在主界面代码,添加using System.Timers;
主要用的是DispatcherTimer
using System.Timers;
DispatcherTimer m_Timer1s = null; //定义1S计时器
TimeSpan _timeSpan = new TimeSpan(0, 0, 0, 0, 0);
/// <summary>
/// 状态
/// </summary>
enum State
{
Start,
Pause,
End
}
/// <summary>
/// 状态
/// </summary>
State _state = State.End;
private void Window_Loaded(object sender, RoutedEventArgs e) //初始化
{
m_Timer1s = new DispatcherTimer();
m_Timer1s.Interval = new TimeSpan(0, 0, 0, 1);
m_Timer1s.Tick += Timer1s_Tick;
m_Timer1s.IsEnabled = true;
//m_Timer1s.Stop();
m_Timer1s.Start();
}
private void Timer1s_Tick(object sender, EventArgs e)//计时执行的程序
{
switch (_state)
{
case State.Start: //开始
{
_timeSpan += new TimeSpan(0, 0, 0, 1);
}
break;
case State.Pause: //暂停
{
}
break;
case State.End: //结束
{
_timeSpan = new TimeSpan(); //结束完就归零,重新开始
//_timeSpan = new TimeSpan(0, 23, 12, 45, 54);
}
break;
}
var time = string.Format("{0:00}:{1:00}:{2:00}", _timeSpan.Hours, _timeSpan.Minutes, _timeSpan.Seconds);
tb_timer.Text = time;
}
代码就是怎么多,其中State.Start,State.End;类似与 DispatcherTimer这个类,设置一个新的对象,如我的: m_Timer1s = new DispatcherTimer();
然后 m_Timer1s.Start(); m_Timer1s.Stop();
start和stop,我都放在串口打开和关闭处,方便看到接受数据用了多长时间。
代码来自于:https://www.cnblogs.com/simonryan/p/3678581.html