You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Double Animation替代Timer实现数值递增计数?

用DoubleAnimation替代Timer实现无限递增计数:可行

完全可以用DoubleAnimation替代DispatcherTimer实现从1开始的无限递增计数,不过DoubleAnimation默认是单次的数值过渡,要实现持续递增,需要在动画完成后动态更新参数并重复触发。

实现方案示例

XAML代码

保留Label控件,添加Storyboard管理动画:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="MainWindow_Loaded">
    <Grid>
        <Label x:Name="myLabel" Content="0"/>
        <Storyboard x:Name="countStoryboard">
            <DoubleAnimation x:Name="countAnimation" 
                             Duration="0:0:1"
                             Completed="CountAnimation_Completed"/>
        </Storyboard>
    </Grid>
</Window>

VB.NET代码

通过动画的Completed事件持续更新数值,实现无限递增:

Class MainWindow
    Private currentCount As Double = 0

    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs)
        StartCountAnimation()
    End Sub

    Private Sub StartCountAnimation()
        currentCount += 1
        countAnimation.From = currentCount - 1
        countAnimation.To = currentCount
        countStoryboard.Begin()
    End Sub

    Private Sub CountAnimation_Completed(sender As Object, e As EventArgs)
        myLabel.Content = currentCount.ToString()
        StartCountAnimation()
    End Sub
End Class

说明

  • 每次动画完成后,将currentCount加1,把动画的起始值设为上一次计数、目标值设为新计数,再重启动画,以此实现每秒递增1的效果。
  • 这种方式依托WPF动画系统处理计时,会自动与UI线程同步,相比DispatcherTimer能避免部分线程调度的潜在问题。

内容的提问来源于stack exchange,提问作者Danny Scofield

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 16:54:26