Files
zijiuqizonghejianyanyi/MainViewModel.cs

70 lines
1.7 KiB
C#
Raw Permalink Normal View History

2026-03-11 15:21:27 +08:00
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();
}
}
}