【发布时间】:2011-12-12 12:21:24
【问题描述】:
我有一个绑定到滚动查看器的文本块来滚动文本。我希望文本在触发按钮单击之类的事件时自动滚动而无需任何用户输入。我尝试使用 ScrollToVerticalOffset 但过渡并不顺畅。无论如何我可以使文本向上平滑滚动。
【问题讨论】:
标签: c# windows-phone-7 scrollviewer
我有一个绑定到滚动查看器的文本块来滚动文本。我希望文本在触发按钮单击之类的事件时自动滚动而无需任何用户输入。我尝试使用 ScrollToVerticalOffset 但过渡并不顺畅。无论如何我可以使文本向上平滑滚动。
【问题讨论】:
标签: c# windows-phone-7 scrollviewer
这是一个示例,我创建了一个名为 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>
在代码隐藏中,我添加了一个 DependencyProperty(我们可以从外部动画),它在每次更改时调用 ScrollViewer 的 ScrollToVerticalOffset() 方法。
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);
}
}
现在您可以将 AnimatableScrollViewer 添加到 PhonePage 并为其设置动画。例如在这样的按钮事件处理程序中:
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();
}
当然,您也可以在您的 xaml 代码中创建动画,这会使其看起来更简洁。现在,ScrollViewer 的内容是固定的……你可以通过向包装类添加更多的依赖属性来改变它。
我不知道这是否是最好的解决方案,事实上它对我来说看起来很丑,但它应该让你知道如何做到这一点。
【讨论】:
animation.Duration = new Duration(new TimeSpan(0, 0, 2)); 在这里你可以修改你的动画所花费的总时间。 2 表示 2 秒
您需要为偏移设置动画。由于无法对偏移属性进行动画处理 - 您要么必须使用自己的动画解决方案来更新每一帧的偏移量,要么为偏移量创建一个附加的依赖属性,该属性将在每次更改时调用 ScrollToVerticalOffset 并且可以进行动画处理。
【讨论】: