Monday, July 6, 2009

Scrolling a TextBlock in WPF

One requirement for a project I've been working on is to scroll text across the screen. I've been playing around with WPF to see if that's the way I should go. Seems to be pretty easy to get the text to scroll, but I haven't been too pleased with it so far. Periodically there's just a touch of choppiness as the text scrolls by. Not bad, but I really need it to be as reliably smooth as possible. I anticipate the next thing I'll try is to write the text out to a bitmap or something and then use graphic routines instead.

I learned a few interesting things as I went, primarily because I have a long way to go in understanding proper layout in WPF. I originally used a Canvas in a StackPanel. The Canvas doesn't provide its content with a MaxWidth so I couldn't figure out a way to reliably wrap the text. I found several posts on forums as I Googled around with the same problem. I finally gave up and just used a Grid with my TextBlock in it. In this final version I played around with various DoubleAnimation features. Rather than hardcoding the "To" property I bound it to the height of the Grid. I also set AutoReverse so the text bounces up and down. That was mostly for my amusement since its not part of the specification. :-) For the application of course I'll want the From and To properties to be off the screen so I need to figure out how much text there is and size those numbers appropriately in code. It won't be the same amount every time in the final application.

Hope the XAML snippet helps someone playing with the same features someday.


<Grid x:Name="OurContainer">
<ScrollViewer VerticalScrollBarVisibility="Hidden">
<TextBlock Text="Some text goes here and it must be long enough to wrap into the next line..."
FontSize="30" TextWrapping="Wrap" />
</ScrollViewer>
<Grid.RenderTransform>
<TranslateTransform x:Name="scroll" />
</Grid.RenderTransform>
<Grid.Triggers>
<EventTrigger RoutedEvent="Canvas.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard RepeatBehavior="Forever" >
<DoubleAnimation From="100"
To="{Binding ElementName=OurContainer, Path=Height}"
Storyboard.TargetName="scroll"
Storyboard.TargetProperty="Y"
Duration="0:0:5" SpeedRatio=".8" AutoReverse="True" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>
</Grid>
</Window>



About The Author

Ron Grove draws on over ten years of training, network administration and development experience. He loves to work with new technology and see how that technology can be best utilized by his clients. You can find him through his company Evanoah, LLC and his LinkedIn profile is here.

0 comments:

Post a Comment