Search code examples
c#xamltexttimertextblock

Text animation, creating typewriting-like effect in c#


This is what I did in MainPage.xaml.cs to create the text animation effect:

private readonly double TEXT_TIMER = 30.0;
private int index;

 private void updateText(String text)
    {
        _text = text;
        index = 0;
        MainTextBlock.Text = "";            

        _textTimer.Tick += _textTimer_Tick;
        _textTimer.Interval = TimeSpan.FromMilliseconds(TEXT_TIMER);
        _textTimer.Start();
    }

 private void _textTimer_Tick(object sender, EventArgs e)
    {
        if (index < _text.Length)
        {
            string s = _text[index].ToString();
            MainTextBlock.Text += s;
            index++;
        }
        else
        {
        _textTimer.Stop();
        }
    }

I have a list of texts/strings and also a button, say NextButton on the MainPage.xaml. The updateText method is in the click event of NextButton, and what it does is to fetch a text from the list of texts/strings and update the textblock using the animation effect.

But I realised that as I continued to click on the NextButton, it was as if the value of TEXT_TIMER was reducing and the animation effect happened more rapidly until there was no animation anymore (i.e. the text just appeared in the textblock without any effects).

Anybody got any idea why this is happening and how I can fix it?

EDIT: I have included code to stop the timer after the textblock has been updated with the hopes that solves possible multiple Tick callbacks but nothing still.


Solution

  • On Dan Bryant's advice:

    My program flow was registering for the Tick event multiple times beacuse I put it into the updateText method which got called multiple times during program run. All I had to do was move that line of code where the Tick event is registered, _textTimer.Tick += _textTimer_Tick; into the constructor, i.e after InitializeComponent() and problem solved!