以下是壹些示例代碼:XAML代碼:<ScrollViewer Width="200" Height="30" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"> <TextBlock x:Name="scrollText" Text="{Binding ScrollText}" Width="Auto" TextWrapping="NoWrap" /></ScrollViewer>
C#:
private void StartScrolling()
{
// 計算TextBlock的寬度
scrollText.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
scrollText.Arrange(new Rect(scrollText.DesiredSize));
double textWidth = scrollText.ActualWidth;
// 創建DoubleAnimation動畫
DoubleAnimation animation = new DoubleAnimation();
animation.From = scrollViewer.ActualWidth;
animation.To = -textWidth;
animation.Duration = TimeSpan.FromSeconds(textWidth / 50); // 滾動速度大約為50像素每秒
animation.Completed += (sender, e) => { StartScrolling(); };
// 綁定動畫的From和To屬性
BindingOperations.SetBinding(animation, DoubleAnimation.FromProperty, new Binding() { Source = scrollViewer, Path = new PropertyPath("ActualWidth") });
BindingOperations.SetBinding(animation, DoubleAnimation.ToProperty, new Binding() { Source = scrollText, Path = new PropertyPath("ActualWidth"), Converter = new NegateConverter() });
// 啟動動畫
scrollText.BeginAnimation(Canvas.LeftProperty, animation);
}
public class NegateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return -System.Convert.ToDouble(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return -System.Convert.ToDouble(value);
}
}