WPF TextBlock 自动滚动动画 
时间: 2023-05-12 09:06:27 浏览: 56
可以使用以下代码实现 WPF TextBlock 的自动滚动动画:
```xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel x:Name="stackPanel">
<TextBlock x:Name="textBlock" TextWrapping="Wrap" FontSize="20" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod, justo vel commodo lacinia, velit magna bibendum sapien, ut commodo elit nulla vitae turpis."></TextBlock>
</StackPanel>
</ScrollViewer>
</Grid>
</Window>
```
```csharp
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 设置 TextBlock 的高度为 ScrollViewer 的高度
textBlock.Height = stackPanel.ActualHeight;
// 创建 DoubleAnimation 对象,设置动画属性
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = 0;
doubleAnimation.To = textBlock.ActualHeight - stackPanel.ActualHeight;
doubleAnimation.Duration = new Duration(new System.TimeSpan(0, 0, 10));
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
// 创建 ScrollViewer 的垂直滚动条的动画
ScrollViewer scrollViewer = (ScrollViewer)stackPanel.Parent;
scrollViewer.BeginAnimation(ScrollViewer.VerticalOffsetProperty, doubleAnimation);
}
}
}
```
这段代码会在 TextBlock 中显示一段文本,并且使用 DoubleAnimation 对象创建一个动画,使得 ScrollViewer 的垂直滚动条自动滚动,从而实现 TextBlock 的自动滚动动画。
相关推荐

















