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);
}
相关推荐
somethingGoWay8 小时前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay10 小时前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
self_myth1 天前
[特殊字符] 深入理解操作系统核心特性:从并发到分布式,从单核到多核的全面解析
windows·macos·wpf·harmonyos
c#上位机1 天前
wpf之TextBlock
c#·wpf
玉面小君3 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
c#上位机3 天前
wpf之Border
c#·wpf
SunflowerCoder3 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans3 天前
WPF中的DataContext以及常见的绑定方式
wpf
没有bug.的程序员4 天前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
somethingGoWay4 天前
wpf 自定义输入ip地址的文本框
wpf