WPF中使用定时器更新元素-DispatcherTimer

  • 在WPF中使用定时器来更新UI元素是一种常见且有用的做法,特别是当你需要基于时间间隔来刷新数据或执行某些操作时。DispatcherTimer是WPF中用于在UI线程上执行周期性任务的理想选择,因为它确保了对UI元素的更新是线程安全的

例子程序

每隔0.5s 界面中的元素更改颜色

Xaml程序

XML 复制代码
<Grid>
    <Rectangle x:Name="BlinkingRectangle" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="Red"/>
</Grid>

CS程序

cs 复制代码
private DispatcherTimer _timer;
private bool _isRed = true;
public Window2()
{
    InitializeComponent();
    // 初始化定时器  
    _timer = new DispatcherTimer();
    _timer.Interval = TimeSpan.FromSeconds(0.5); // 每0.5秒切换一次颜色  
    _timer.Tick += Timer_Tick; // 设置Tick事件处理程序  
    _timer.Start(); // 启动定时器 
}

private void Timer_Tick(object sender, EventArgs e)
{
    // 切换颜色  
    if (_isRed)
    {
        BlinkingRectangle.Fill = new SolidColorBrush(Colors.Green);
        _isRed = false;
        Console.WriteLine("绿色");
    }
    else
    {
        BlinkingRectangle.Fill = new SolidColorBrush(Colors.Red);
        _isRed = true;
        Console.WriteLine("红色");
    }
}

// 确保在窗口关闭时停止定时器  
protected override void OnClosed(EventArgs e)
{
    _timer.Stop();
    base.OnClosed(e);
}
相关推荐
Scout-leaf7 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
柒.梧.9 天前
基于SpringBoot+JWT 实现Token登录认证与登录人信息查询
wpf
十月南城12 天前
Flink实时计算心智模型——流、窗口、水位线、状态与Checkpoint的协作
大数据·flink·wpf
听麟15 天前
HarmonyOS 6.0+ 跨端会议助手APP开发实战:多设备接续与智能纪要全流程落地
分布式·深度学习·华为·区块链·wpf·harmonyos
@hdd15 天前
Kubernetes 可观测性:Prometheus 监控、日志采集与告警
云原生·kubernetes·wpf·prometheus
zls36536515 天前
C# WPF canvas中绘制缺陷分布map
开发语言·c#·wpf
专注VB编程开发20年15 天前
c#Redis扣款锁的设计,多用户,多台电脑操作
wpf
闲人编程16 天前
定时任务与周期性调度
分布式·python·wpf·调度·cron·定时人物·周期性
zls36536516 天前
C# WPF canvas中绘制缺陷分布map并实现缩放
开发语言·c#·wpf
数据知道17 天前
PostgreSQL:Citus 分布式拓展,水平分片,支持海量数据与高并发
分布式·postgresql·wpf