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);
}
相关推荐
FuckPatience12 小时前
WPF 使用UserControl / ContentControl显示子界面
wpf
wangnaisheng16 小时前
【WPF】WrapPanel的用法
wpf
源之缘-OFD先行者1 天前
10 万雷达点迹零卡顿回放:WPF + Vortice.Direct2D 多线程渲染实战
wpf
猫林老师1 天前
Flutter for HarmonyOS开发指南(九):测试、调试与质量保障体系
flutter·wpf·harmonyos
LateFrames2 天前
做【秒开】的程序:WPF / WinForm / WinUI3 / Electron
electron·c#·wpf·winform·winui3·claude code
beyond谚语2 天前
第四章 依赖项属性
wpf
国服第二切图仔2 天前
鸿蒙应用开发之实现键值型数据库跨设备数据同步
数据库·wpf·harmonyos
玖笙&3 天前
✨WPF编程进阶【7.1】动画基础
c++·c#·wpf·visual studio
专注VB编程开发20年3 天前
探讨vs2022在net6框架wpf界面下使用winform控件
framework·.net·wpf·winform·cefsharp·miniblink·geckofx45
刘一说3 天前
Spring Boot 中的定时任务:从基础调度到高可用实践
spring boot·后端·wpf