简体   繁体   中英

Animate the Text property of a TextBlock

I am quite new to WP develoment and am currently playing around with animations. What I am now trying to do is animate the Text property of a TextBlock.

For training purposes, I am developping a simple temperature convertion app and there is a big number on the screen (the temperature) that I would like to gradually increase or decrease until it reaches another value (for instance from 10 to 24 by displaying every number inbetween).

I tried using a storyboard on the text property but as I thought it doesn't work. Then I tried setting the property to each value one by one (for loop) but the view dons't refresh regularly enough and the app blocks until the loop finishes and displays only the last value. I don't know if what I would like to do is possible (I hope it is it's not that uncommon, right?) and I have no other idea to get the result I would like. Does anyone has an idea about that?

Thanks :)

You may use a DispatcherTimer , and update the TextBlock's Text property in its Tick event handler:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM