2011-12-12 58 views
3

我有一个文本块绑定到滚动查看器来滚动文本。当点击按钮点击等事件发生时,我希望文本自动滚动,无需任何用户输入。我试过使用ScrollToVerticalOffset,但过渡并不顺利。无论如何,我可以让文本顺利向上滚动。在WP7中滚动查看器文本块滚动

回答

5

这里是一个例子,我创建了一个叫做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添加到电话页面并对其进行动画处理。例如,在一个按钮事件处理像这样的:

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的内容是固定的......你可以通过向包装类添加更多的依赖属性来改变它。

我不知道这是否是最好的解决方案,实际上它对我来说看起来相当丑陋,但它应该让你知道它是如何完成的。

+0

我创建了一个新的WP7项目。将AnimatableScrollViewer.xaml&.xaml.cs添加到项目中。我试图使用cmdScroll_Click函数中的代码。但我没有开始动画。我想我需要在我的MainPage.xaml中使用这个控件。请让我知道是否需要将此用户控件包含在我的应用程序主页xaml中。 – Mugu

+0

对不起,我设法弄清楚了。无论如何,感谢您的帮助。只需要一个更多的帮助。 Incase我想让动画变慢应该对代码进行哪些修改? – Mugu

+0

在点击处理程序中有一行'animation.Duration = new Duration(new TimeSpan(0,0,2));'这里您可以修改动画的总时间。 2意味着2秒 –

0

您需要动画偏移量。由于偏移属性不能动画 - 您必须使用您自己的动画解决方案来更新每帧的偏移量,或者为每次更改都会调用ScrollToVerticalOffset的偏移量创建附加的依赖项属性,并且具有动画效果。