Search code examples
c#.netwpfflowdocument

Scroll a WPF FlowDocumentScrollViewer from code?


I have a FlowDocumentScrollViewer I want to automatically scroll to the bottom when text is added.

<FlowDocumentScrollViewer Name="Scroller">
 <FlowDocument Foreground="White" Name="docDebug" FontFamily="Terminal">
  <Paragraph Name="paragraphDebug"/>
 </FlowDocument>
</FlowDocumentScrollViewer>

In code I add Inlines to the Paragraph, but when there is to much text I would like to be able to simply scroll down using code instead of having the user doing so.

Any suggestions?


Solution

  • The other answers given here are a bit puzzling, since I don't see any public "ScrollViewer" property on the FlowDocumentScrollViewer.

    I hacked around the problem like this. Beware that this method can return null during initialization:

    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;
    }