为 TextBlock 的文本 属性 设置动画

Animate the Text property of a TextBlock

我对 WP 开发还很陌生,目前正在研究动画。 我现在要做的是为 TextBlock 的文本 属性 设置动画。

出于培训目的,我正在开发一个简单的温度转换应用程序,屏幕上有一个很大的数字(温度),我想逐渐增加或减少它直到达到另一个值(例如从 10 到24 通过显示中间的每个数字)。

我尝试在文本 属性 上使用故事板,但我认为它不起作用。然后我尝试将 属性 一个一个地设置为每个值(for 循环),但视图刷新不够规律,应用程序会阻塞,直到循环完成并仅显示最后一个值。 我不知道我想做的事情是否可行(我希望这不是那么罕见,对吧?)而且我没有其他想法来获得我想要的结果。 有人对此有想法吗?

谢谢:)

您可以使用 DispatcherTimer,并在其 Tick 事件处理程序中更新 TextBlock 的文本 属性:

private readonly DispatcherTimer timer = new DispatcherTimer();
private int currentValue;
private int endValue;

public MainPage()
{
    ...
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += TimerTick;
}

private void TimerTick(object sender, object e)
{
    currentValue++;
    textBlock.Text = currentValue.ToString();

    if (currentValue >= endValue)
    {
        timer.Stop();
    }
}

private void AnimateText(int start, int end)
{
    currentValue = start;
    endValue = end;
    textBlock.Text = currentValue.ToString();

    if (currentValue < endValue)
    {
        timer.Start();
    }
}