DispatcherTimer 控件[WPF]
注意:“Timer”和“DispatcherTimer”的区别:
Timer必须使用this.Dispatcher.BeginInvoke去更新UI,DispatcherTimer 可以直接更新UI
这两者区别是 Timer在非UI线程跑的,DispatcherTimer是在UI线程跑的。
需要注意的是在WPF中涉及到界面操作的话,一定要使用DispatcherTimer,DispatcherTimer是为WPF专门设计的,不然的话会提示界面资源被其他线程所拥有而无法更新界面。
案例:钟表
ViewModel代码
///设置更新间隔 1000ms=1s TimeSpan.FromMilliseconds(1000)或dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
internal partial class TutorialLevelViewModel:ObservableObject { [ObservableProperty] private string? countDown; public TutorialLevelViewModel() { dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1000); ///设置更新间隔 1000ms=1s TimeSpan.FromMilliseconds(1000)或dispatcherTimer.Interval = new TimeSpan(0,0,1); dispatcherTimer.Interval = new TimeSpan(0,0,1); dispatcherTimer.Tick += (c, s) => { CountDown= DateTime.Now.ToString("HH:mm:ss.fff"); }; dispatcherTimer.Start(); } }
View 代码
<Label Style="{StaticResource TimerStyle}" Grid.Column="2" Grid.Row="0" Content="{Binding CountDown}" Margin="200,0,0,0" Height="43" Width="215"></Label>
案例:倒计时
///倒计时
注意 TimeSpan格式化方式 的 @"hh\:mm\:ss"
internal partial class TutorialLevelViewModel:ObservableObject { [ObservableProperty] private string? countDown; //练习开始时间 private DateTime startime; //练习结束时间 private DateTime endtime; public TutorialLevelViewModel() { ///设置更新间隔 1000ms=1s TimeSpan.FromMilliseconds(1000)或dispatcherTimer.Interval = new TimeSpan(0,0,1); dispatcherTimer.Interval = new TimeSpan(0,0,1); startime = DateTime.Now; endtime = DateTime.Now + new TimeSpan(0, 10, 0); ///倒计时 TimeSpan 格式方式_countDown.ToString(@"hh\:mm\:ss") dispatcherTimer.Tick += (c, s) => { var _countDown = endtime - DateTime.Now; CountDown = _countDown.ToString(@"hh\:mm\:ss"); }; dispatcherTimer.Start(); } }
View 代码
<Label Style="{StaticResource TimerStyle}"
Grid.Column="2"
Grid.Row="0"
Content="{Binding CountDown}"
Margin="200,0,0,0" Height="43" Width="215"></Label>
编程是个人爱好