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

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

例子程序

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

Xaml程序

<Grid>
    <Rectangle x:Name="BlinkingRectangle" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="Red"/>
</Grid>

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);
}

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值