繁体   English   中英

在WP7中滚动查看器文本块滚动

[英]scroll viewer text block scrolling in WP7

我有一个绑定到滚动查看器的文本块来滚动文本。 我希望文本在触发按钮点击等事件时自动滚动而不显示任何用户输入。 我尝试使用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>

在代码隐藏中,我添加了一个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的内容是固定的......您可以通过向包装类添加更多依赖项属性来使其更改。

我不知道这是不是最好的解决方案,事实上它对我来说看起来很难看,但它应该让你知道如何做到这一点。

您需要为偏移设置动画。 由于无法对偏移属性进行动画处理 - 您必须使用自己的动画解决方案来更新每帧的偏移量,或者为每次更改时调用ScrollToVerticalOffset的偏移量创建附加的依赖项属性,并且可以进行动画处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM