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);
}
相关推荐
heimeiyingwang2 小时前
【架构实战】状态机架构:订单/工单状态流转设计
观察者模式·架构·wpf
LCG元4 小时前
STM32项目实战:基于STM32F103的智能农业监控系统
stm32·单片机·嵌入式硬件
Truffle7电子7 小时前
STM32CubeIDE/Programmer/Touch GFX 应用
stm32·单片机·嵌入式硬件
constant_LDX7 小时前
步进电机开发(一、硬件设计)
单片机·嵌入式硬件
richxu202510018 小时前
嵌入式学习之路->stm32篇->(14)通用定时器(上)
stm32·单片机·嵌入式硬件·学习
Deitymoon8 小时前
STM32——串口通信(USART)
单片机·嵌入式硬件
iCxhust8 小时前
微机原理实践教程(C语言篇)---A002流水灯
c语言·开发语言·单片机·嵌入式硬件·51单片机·课程设计·微机原理
Deitymoon10 小时前
STM32——外部中断按键控制led
stm32·单片机·嵌入式硬件
czwxkn10 小时前
7STM32(stdl)flash内部闪存
stm32·单片机·嵌入式硬件
咕噜咕噜啦啦10 小时前
STlink下载程序
stm32·单片机