WPF定时器

DispatcherTimer定时器,可以说是专门为WPF界面设计的定时器。因为这个定时器是和UI都在同一线程上的。

添加命名空间引用

cs 复制代码
using System.Windows.Threading;

实例化

cs 复制代码
DispatcherTimer _timer = new DispatcherTimer();

设定定时器参数

cs 复制代码
 /*设置定时时间方法一*/
 _timer.Interval = new TimeSpan(0,1,0);//设置时间间隔h,m,s

 /*设置定时时间方法二*/
 timer.Interval = TimeSpan.FromMilliseconds(100);//设置的间隔为100ms

 _timer.Tick += Timer_Tick;//绑定计时事件(Tick事件在UI线程执行)

 _timer.DispatcherPriority = DispatcherPriority.Normal;//可选:设置定时器优先级(默认Normal)

启动、停止、修改定时时间

cs 复制代码
// 重启定时器
_timer.Start();

// 暂停定时器
_timer.Stop();

// 修改时间间隔(需先停止再修改,或直接修改后生效)
_timer.Interval = TimeSpan.FromMilliseconds(500); // 改为500ms触发一次
Tick 事件处理(更新 UI)
cs 复制代码
private void Timer_Tick(object sender, EventArgs e)
{
    _count++;
    // 直接更新UI控件(安全,因为在UI线程)
    lblTimer.Content = $"计时:{_count}秒";
    
    // 示例:计时到10秒停止
    if (_count >= 10)
    {
        _timer.Stop();
        lblTimer.Content = "计时结束!";
    }
}

实例

cs 复制代码
using System.Windows;
using System.Windows.Threading;

public partial class MainWindow : Window
{
    private DispatcherTimer _timer;
    private int _count = 0;

    public MainWindow()
    {
        InitializeComponent();
        
        // 1. 创建DispatcherTimer实例
        _timer = new DispatcherTimer();
        
        // 2. 设置时间间隔(单位:毫秒)
        _timer.Interval = TimeSpan.FromSeconds(1); // 每秒触发一次
        
        // 3. 绑定计时事件(Tick事件在UI线程执行)
        _timer.Tick += Timer_Tick;
        
        // 4. 可选:设置定时器优先级(默认Normal)
        _timer.DispatcherPriority = DispatcherPriority.Normal;
        
        // 5. 启动定时器
        _timer.Start();
    }
}
Tick 事件处理(更新 UI)
cs 复制代码
private void Timer_Tick(object sender, EventArgs e)
{
    _count++;
    // 直接更新UI控件(安全,因为在UI线程)
    lblTimer.Content = $"计时:{_count}秒";
    
    // 示例:计时到10秒停止
    if (_count >= 10)
    {
        _timer.Stop();
        lblTimer.Content = "计时结束!";
    }
}

label显示定时数据

复制代码
<!-- 用于数字自增显示 -->
<Label x:Name="counterLabel"
        Content="0"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Margin="20,20,0,0"
        FontSize="20"
        Padding="6"/>

private void timer_Tick(object? sender, EventArgs e)
{
    // 每次 Tick 自增并显示计数
    cnt++;
    Debug.WriteLine($"[{DateTime.Now:HH:mm:ss}] DispatcherTimer Tick 触发。cnt={cnt}");

    // DispatcherTimer 在 UI 线程运行,可以直接更新控件;使用 null-条件以防控件未命名或未初始化
    counterLabel?.SetValue(ContentControl.ContentProperty, cnt);
}
相关推荐
北域码匠3 小时前
高通滤波算法深度解析(High-Pass Filter)
stm32·算法·c#·数字信号处理·嵌入式开发·滤波算法·高通滤波
star learning white4 小时前
STM32入门学习5
stm32·嵌入式硬件·学习
新晨单片机设计4 小时前
S006A-基于STM32单片机温湿度检测系统【Proteus仿真+Keil程序+原理图】
stm32·单片机·proteus
mengge.cloud5 小时前
存储技术基础小白教程
linux·运维·服务器·wpf·存储
逐步前行6 小时前
ESP32-S3-分区表(Partition Table)
单片机
星河单片机6 小时前
STM32驱动HS‑S37A水位传感器+OLED完整实验讲解
stm32·单片机·嵌入式硬件
一条破秋裤7 小时前
16_TIM编码器接口测速
笔记·stm32·学习
糖糖单片机设计8 小时前
STM32水稻苗大棚环境监测系统
stm32·单片机·嵌入式硬件
star learning white9 小时前
STM32入门学习3
stm32·单片机·学习
jianqiang.xue9 小时前
审查技能库(上):内存安全四件套
stm32·单片机·物联网·架构·esp32