是否可以从代码中滚动ScrollViewer
?
如果是,如何?
如果否,您可以建议一些解决方法以获得类似的效果。我有一个包含RichTextBox的ScrollViewer,我想从代码中滚动内容。
答案 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"/>
,其中SmoothScroll
是ScrollViewer
对象。
在此阶段,您可以在Mediator
对象上创建所需的任何动画,以设置滚动动画