我有一个文本块绑定到一个滚动查看器来滚动文本。当某些事件(比如点击按钮)被触发时,我希望文本能够自动滚动,而不需要用户输入。我尝试使用ScrollToVerticalOffset,但过渡效果不够平滑。是否有任何方法可以使文本向上平滑滚动。
我有一个文本块绑定到一个滚动查看器来滚动文本。当某些事件(比如点击按钮)被触发时,我希望文本能够自动滚动,而不需要用户输入。我尝试使用ScrollToVerticalOffset,但过渡效果不够平滑。是否有任何方法可以使文本向上平滑滚动。
这里有一个示例,我创建了一个称为AnimatableScrollViewer的包装控件,它包含一个普通的ScrollViewer和一个TextBlock。
<UserControl>
<Grid x:Name="LayoutRoot" Background="Transparent">
<ScrollViewer x:Name="scrollViewer" Width="{Binding ActualWidth, ElementName=userControl, Mode=OneWay}" Height="{Binding ActualHeight, ElementName=userControl, Mode=OneWay}">
<TextBlock TextWrapping="Wrap" Text="Add some pretty long text here..."/>
</ScrollViewer>
</Grid>
</UserControl>
public partial class AnimatableScrollViewer : UserControl
{
public static readonly DependencyProperty AnimatablOffsetProperty = DependencyProperty.Register("AnimatableOffset",
typeof(double), typeof(AnimatableScrollViewer), new PropertyMetadata(AnimatableOffsetPropertyChanged));
public double AnimatableOffset
{
get { return (double)this.GetValue(AnimatablOffsetProperty); }
set { this.SetValue(AnimatablOffsetProperty, value); }
}
public AnimatableScrollViewer()
{
InitializeComponent();
AnimatableOffset = scrollViewer.VerticalOffset;
}
private static void AnimatableOffsetPropertyChanged(object sender, DependencyPropertyChangedEventArgs args)
{
AnimatableScrollViewer cThis = sender as AnimatableScrollViewer;
cThis.scrollViewer.ScrollToVerticalOffset((double)args.NewValue);
}
}
private void cmdScroll_Click(object sender, RoutedEventArgs e)
{
// Calculate target offset
double targetOffset = 1000;
// Create animation and storyboard
DoubleAnimation animation = new DoubleAnimation();
animation.EasingFunction = new CircleEase();
animation.Duration = new Duration(new TimeSpan(0, 0, 2));
animation.From = animatableScrollViewer.AnimatableOffset;
animation.To = targetOffset;
Storyboard.SetTarget(animation, animatableScrollViewer);
Storyboard.SetTargetProperty(animation, new PropertyPath("(AnimatableScrollViewer.AnimatableOffset)"));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(animation);
storyboard.Begin();
}
您需要对偏移量进行动画处理。由于偏移属性无法进行动画处理,因此您需要使用自己的动画解决方案来更新每一帧的偏移量,或者创建一个附加依赖属性来处理偏移量,该属性在每次更改时调用ScrollToVerticalOffset,并且可以进行动画处理。
animation.Duration = new Duration(new TimeSpan(0, 0, 2));
在这里,您可以修改动画所需的总时间。数字 2 表示 2 秒。 - Patrick Schmidt