注意:“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>