从代码中滚动WPF FlowDocumentScrollViewer?

我有一个FlowDocumentScrollViewer我想在添加文本时自动滚动到底部。

     

在代码中我向段落添加了内联,但是当有很多文本时,我希望能够简单地使用代码向下滚动而不是让用户这样做。

有什么建议?

这里给出的其他答案有点令人费解,因为我没有在FlowDocumentScrollViewer上看到任何公共“ScrollViewer”属性。

我这样解决了这个问题。 请注意,此方法在初始化期间可以返回null:

 public static ScrollViewer FindScrollViewer(this FlowDocumentScrollViewer flowDocumentScrollViewer) { if (VisualTreeHelper.GetChildrenCount(flowDocumentScrollViewer) == 0) { return null; } // Border is the first child of first child of a ScrolldocumentViewer DependencyObject firstChild = VisualTreeHelper.GetChild(flowDocumentScrollViewer, 0); if (firstChild == null) { return null; } Decorator border = VisualTreeHelper.GetChild(firstChild, 0) as Decorator; if (border == null) { return null; } return border.Child as ScrollViewer; } 

尝试:

 Scroller.ScrollViewer.ScrollToEnd(); 

其中“Scroller”是FlowDocumentScrollViewer的名称。

编辑 :我写这个答案有点太快了。 FlowDocumentScrollViewer不公开ScrollViewer属性。 我实际上扩展了FlowDocumentScrollViewer类并自己实现了ScrollViewer属性。 这是实施:

  ///  /// Backing store for the  property. ///  private ScrollViewer scrollViewer; ///  /// Gets the scroll viewer contained within the FlowDocumentScrollViewer control ///  public ScrollViewer ScrollViewer { get { if (this.scrollViewer == null) { DependencyObject obj = this; do { if (VisualTreeHelper.GetChildrenCount(obj) > 0) obj = VisualTreeHelper.GetChild(obj as Visual, 0); else return null; } while (!(obj is ScrollViewer)); this.scrollViewer = obj as ScrollViewer; } return this.scrollViewer; } } 

我遇到了类似的问题:我想要一个文本区域 ,它可以保存我的文本,能够包装它,它填充其父控件并可滚动。

首先,我尝试使用带有ScrollViewerTextBlock ,我认为它有效,但出于某种原因,我想使用FlowDocument代替FlowDocumentScrollViewer 。 后者不起作用,我只是无法放弃战斗,所以我试图找到解决方案,这就是我到这里的方式。 我试图应用原始问题的答案中提供的解决方法,但是我找不到任何解决方案(我使用的是.NET 4.5,也许它适用于其他版本,但我不知道这一点)。

我也试过单独使用一个FlowDocument ,但是控件包含了一些我不想要的UI元素。 所以,我提出了另一个解决方案。

     

那就对了。 有用! 调用ScrollViewer.ScrollToBottom()就可以了! ScrollViewer启用滚动, FlowDocumentScrollViewerFlowDocument中删除UI元素。 希望能帮助到你!


显然我的构造有一个缺陷,因为这样FlowDocument不能通过鼠标的滚轮滚动。 但是,将FlowDocumentScrollViewer控件的IsHitTestVisible属性设置为False可解决此问题。

7年前问过这个问题,现在我遇到了同样的问题,我找到了一个简单的解决方案。 以下代码将一个Section添加到Flowdocument,它与Paragraph相同,然后滚动到结尾。

 private void addSection(Section section) { section.Loaded += section_Loaded; fdoc.Blocks.Add(section); } private void section_Loaded(object sender, RoutedEventArgs e)//scroll to end { var sec = sender as Section; if (sec != null) { sec.BringIntoView(); } } 

这可能是一个非常晚的答案,但我找到了一种方法来做到这一点。

 //after your FlowDocumentScrollViewer(for example, x:Name="fdsv") loaded ScrollViewer sv = fdsv.Template.FindName("PART_ContentHost", fdsv) as ScrollViewer; sv.ScrollToBottom(); sv.ScrollToTop(); sv.ScrollToVerticalOffset(100); // etc. 

检查IScrollInfo和ScrollViewer以获取详细信息。

我希望这可以帮助你。