WPF Marquee Text Animation

后端 未结 4 1146
醉梦人生
醉梦人生 2020-11-27 18:01

I can scroll text with TranslateTransform but when the animation is close to finishing I\'d like it to begin again. Like a snake :)

This is what I\'ve g

4条回答
  •  被撕碎了的回忆
    2020-11-27 18:33

    Something like this should do the trick.

    You can add a Canvas to the StackPanel with 2 TextBlocks one set to position 0 and one set to the ActualWidth of the StackPanel, then when the first block of text goes offscreen the other block will come into view.

    The reason I used Canvas is because Canvas is the only element that actually supports ClipToBounds="false" this allows the 2nd TextBlock to be visible even if its placed outside the bounds of the Canvas itself

    We also need a IValueConverter to get the correct negative value if you want to scroll from right to left.

    I also added event trigger on SizeChanged so if the window is resized the animation values will update correctly.

    Code:

    namespace WpfApplication9
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
    
            public MainWindow()
            {
                InitializeComponent();
            }
        }
    
        public class NegatingConverter : IValueConverter
        {
    
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (value is double)
                {
                    return -((double)value);
                }
                return value;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (value is double)
                {
                    return +(double)value;
                }
                return value;
            }
        }
    }
    

    Xaml:

    
        
            
                
                
                    
                
            
            
                
            
            
                
                    
                
                
                    
                
            
            
                
                
            
        
    
    

    Result:

    enter image description here enter image description here

    Edit: Left to Right

     
            
                
                
                    
                
            
            
                
            
            
                
                    
                
                
                    
                
            
            
                
                
            
        
    

提交回复
热议问题