Scrolling Text animation in WPF
Scrolling Text animation in WPF
In one of our WPF applications we came across the need to present static data that is larger then it’s container (grid/text block/panel). We could have chosen to reduce the font size, but this was inappropriate for our situation because the application was intended to appear on a LCD screen and be seen from as far as possible.
We decided to present the text inside a text block and scroll it (bottom to top) if it became too large for the text block.
After quite a few trail and error attempts we succeeded in creating the required scrolling text.
We started by adding a RenderTransform behavior to the text block that’s showing the scrollable text. Using RenderTransform you may take the control and move it, resize it, rotate it and so on.
<TextBlock Name="RollText" Grid.Row="1" Foreground="White" TextAlignment="Center">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="translate" />
</TextBlock.RenderTransform>
</TextBlock>
After adding the text to the text block, the scrolling animation can be done by adding DoubleAnimation to a StoryBoard.
We create the DoubleAnimation object and set where we wish the animation to begin and where it ends together with the animation duration.
animation.From = RollText.ActualHeight;
animation.To = RollText.ActualHeight * -1;
animation.Duration = TimeSpan.FromSeconds(10);
Next we set the target element which in our case is the translate transform of the text block.
Storyboard.SetTargetName(animation, "translate");
Now we set the target dependency property that will be changed by the animation and add the animation to the storyboard. The dependency property we set as target is the “Y” position of the target element selected above, this will enable the text block to move on the Y axis from bottom to top.
PropertyPath propPath = new PropertyPath("Y");
Storyboard.SetTargetProperty(animation, propPath);
storyboard.Children.Add(animation);
The last thing left to do is to run the storyboard.
storyboard.RepeatBehavior = RepeatBehavior.Forever;
storyboard.Begin(RollText, true);
You can download the code here.