可以通过编程方式滚动Windows手机中的滚动查看器吗?

时间:2014-03-10 18:31:52

标签: windows-phone-7 windows-phone-8

是否可以从代码中滚动ScrollViewer

如果是,如何?

如果否,您可以建议一些解决方法以获得类似的效果。我有一个包含RichTextBox的ScrollViewer,我想从代码中滚动内容。

1 个答案:

答案 0 :(得分:0)

ScrollViewer.ScrollToVerticallOffset()立即滚动以提供偏移量

如果您需要使用简单函数进行平滑滚动,首先要创建允许绑定到ScrollViewer的类:

public class ScrollViewerOffsetMediator : FrameworkElement
{
    /// <summary>
    /// ScrollViewer instance to forward Offset changes on to.
    /// </summary>
    public ScrollViewer ScrollViewer
    {
        get { return (ScrollViewer)GetValue(ScrollViewerProperty); }
        set { SetValue(ScrollViewerProperty, value); }
    }
    public static readonly DependencyProperty ScrollViewerProperty =
        DependencyProperty.Register(
            "ScrollViewer",
            typeof(ScrollViewer),
            typeof(ScrollViewerOffsetMediator),
            new PropertyMetadata(OnScrollViewerChanged));
    private static void OnScrollViewerChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var mediator = (ScrollViewerOffsetMediator)o;
        var scrollViewer = (ScrollViewer)(e.NewValue);
        if (null != scrollViewer)
        {
            scrollViewer.ScrollToVerticalOffset(mediator.VerticalOffset);
        }
    }

    /// <summary>
    /// VerticalOffset property to forward to the ScrollViewer.
    /// </summary>
    public double VerticalOffset
    {
        get { return (double)GetValue(VerticalOffsetProperty); }
        set { SetValue(VerticalOffsetProperty, value); }
    }
    public static readonly DependencyProperty VerticalOffsetProperty =
        DependencyProperty.Register(
            "VerticalOffset",
            typeof(double),
            typeof(ScrollViewerOffsetMediator),
            new PropertyMetadata(OnVerticalOffsetChanged));
    public static void OnVerticalOffsetChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var mediator = (ScrollViewerOffsetMediator)o;
        if (null != mediator.ScrollViewer)
        {
            mediator.ScrollViewer.ScrollToVerticalOffset((double)(e.NewValue));
        }
    }
}

比添加到xaml:

<my:ScrollViewerOffsetMediator x:Name="Mediator" ScrollViewer="{Binding ElementName=SmoothScroll}" Margin="0" VerticalAlignment="Top"/>

,其中SmoothScrollScrollViewer对象。

在此阶段,您可以在Mediator对象上创建所需的任何动画,以设置滚动动画