WPF显示日期时间,不跳秒
标签: C# ; WPF
- 常规: 利用
DispatcherTimer
实例,通过Tick
时间每间隔一秒调用一次timer_Tick
方法(自定义),即输出一次日期、时间。通过RaisePropertyChanged
(//prism)通知到前端。
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 0, 1);
timer.Tick += timer_Tick;
timer.IsEnabled = true;
}
/**************************************************************/
/*当前日期*/
private string _DateNow;
public string DateNow
{
get { return _DateNow; }
set { _DateNow = value; RaisePropertyChanged(); }
}
/*当前时间*/
private string _TimeNow;
public string TimeNow
{
get { return _TimeNow; }
set { _TimeNow = value; RaisePropertyChanged(); }
}
/*事件处理器*/
private void timer_Tick(object sender, EventArgs e)
{
DateNow = DateTime.Now.ToString("yyyy-MM-dd ");
TimeNow = DateTime.Now.ToString("HH:mm:ss");
}
}
- 注意: .NET只保证
Tick
事件 不会提前执行,但不保证其会及时执行 ,所以有一定概率会出现 “跳秒” ,所以可为DispatcherTimer
设置高优先级(按需)。如下:
/**********原构造函数修改为:**********/
public MainWindowViewModel()
{
var priority=new DispatcherPriority();
priority = DispatcherPriority.Send;
DispatcherTimer timer = new DispatcherTimer(priority);
timer.Interval = new TimeSpan(0, 0, 0, 1);
timer.Tick += timer_Tick;
timer.IsEnabled = true;
}
- 前端代码如下:
<TextBlock
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="18"
Text="{Binding TimeNow}" />
<TextBlock
Grid.Column="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="18"
Text="{Binding DateNow}" />
- 效果如下