Creating marquee/scrolling text in WPF
A WPF marquee is a scrolling piece of text displayed either horizontally across or vertically down your container. Here i show you how to make a scrolling marquee using Canvas and TextBlock. I will show only left to right in code. However, you can achieve right to left or vertical marquee text just by changing some portion of code using the same technique.
The following three techniques are used to achieve marquee animation:
- Negative Positioning in canvas: If we set negative value to any of the positioning property of Canvas: Left, Right, Top and Bottom for an UIelement , Canvas draws that Uielement outside of Canvas area.
- ClipToBounds property of canvas: if you set the value of the ClipToBounds property to true, Canvas will clip its children when they go outside of Canvas.
- Changing Position of Uielement continuously: By changing continuously any of the canvas positioning property Left, right, Top, Bottom we can get moving text.
How is Left to right marquee text implemented in this sample?
Here a canvas is used as the container of marquee text. To move the text outside of canvas negative Left property of canvas is used. However, if someone uses negative left property of canvas, it will go outside of its parent container but will still remain visible outside of the parent container. To make marquee text invisible outside of canvas CliptoBound property is used. Then using double animation left property of canvas for that element is being changed continuously to get moving text. The whole thing is done using the following code.
1: void Window1_Loaded(object sender, RoutedEventArgs e)
2: {
3: DoubleAnimation doubleAnimation = new DoubleAnimation();
4: doubleAnimation.From = -tbmarquee.ActualWidth;
5: doubleAnimation.To = canMain.ActualWidth;
6: doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
7: doubleAnimation.Duration = new Duration(TimeSpan.Parse("0:0:10"));
8: tbmarquee.BeginAnimation(Canvas.LeftProperty, doubleAnimation);
9: }
For Left to right marquee: use Left Property of Canvas
For right to left marquee: use Right Property of Canvas
For upward marquee: use Bottom Property of Canvas
For Downward marquee: use Top Property of Canvas
The used XAML for this is in the following
1: <Window x:Class="MarqueText.Window1"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="Window1" Height="500" Width="700" >
5: <Canvas Background="White" >
6: <Canvas Margin="50" Canvas.Left="150" Canvas.Top="100" ClipToBounds="True" Name="canMain" Background="Red" Height="100" Width="300" >
7: <TextBlock Margin="0,40" FontSize="25" Name="tbmarquee">Bangladesh</TextBlock>
8: </Canvas>
9: </Canvas>
10: </Window>
You can download the sample code from here. Hope this will save some of your time.