using System; using System.Timers; using 自救器呼吸器综合检验仪; namespace 自救器呼吸器综合检验仪 { public class MainViewModel : NotifyPropertyChangedBase { private DateTime _currentTime; private readonly Timer _timer; // 可绑定的当前时间属性 public DateTime CurrentTime { get => _currentTime; set => SetField(ref _currentTime, value); } public MainViewModel() { // 初始化当前时间 CurrentTime = DateTime.Now; // 创建定时器,每隔1秒触发一次 _timer = new Timer(1000); _timer.Elapsed += Timer_Elapsed; _timer.Start(); } private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { // 检查应用程序是否还在运行 if (App.Current == null || App.Current.Dispatcher == null) { StopTimer(); return; } try { App.Current.Dispatcher.Invoke(() => { CurrentTime = DateTime.Now; }); } catch { // 应用程序关闭时忽略异常 StopTimer(); } } public void StopTimer() { if (_timer != null) { _timer.Stop(); _timer.Elapsed -= Timer_Elapsed; _timer.Dispose(); } } // 释放定时器资源(避免内存泄漏) public void Dispose() { _timer?.Stop(); _timer?.Dispose(); } } }