WPF TextBlock 自动滚动动画
时间: 2023-05-12 19:06:30 浏览: 257
可以使用以下代码实现 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 Text="This is line 1" />
<TextBlock Text="This is line 2" />
<TextBlock Text="This is line 3" />
<TextBlock Text="This is line 4" />
<TextBlock Text="This is line 5" />
<TextBlock Text="This is line 6" />
<TextBlock Text="This is line 7" />
<TextBlock Text="This is line 8" />
<TextBlock Text="This is line 9" />
<TextBlock Text="This is line 10" />
</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();
// Start the animation when the window is loaded
Loaded += (sender, e) =>
{
var storyboard = new Storyboard();
var animation = new DoubleAnimation
{
From = 0,
To = stackPanel.ActualHeight - scrollViewer.ActualHeight,
Duration = new Duration(new System.TimeSpan(0, 0, 5)),
RepeatBehavior = RepeatBehavior.Forever
};
Storyboard.SetTarget(animation, scrollViewer);
Storyboard.SetTargetProperty(animation, new PropertyPath(ScrollViewer.VerticalOffsetProperty));
storyboard.Children.Add(animation);
storyboard.Begin();
};
}
}
}
```
这段代码会在窗口加载时启动一个动画,使得 TextBlock 中的内容自动向上滚动。
阅读全文