PPFY
PPFY

Reputation: 67

In a WPF, how do you scroll to the bottom of a FlowDocumentScrollViewer?

A normal ScrollViewer appears to have a method that accomplishes this. A FlowDocumentScrollViewer does not. So how do I go around setting a FlowDocumentScrollViewer to the bottom.

Upvotes: 4

Views: 606

Answers (2)

rmojab63
rmojab63

Reputation: 3631

Or you can use the provided answer here, and search for the ScrollViewer:

public static void ScrollToEnd(FlowDocumentScrollViewer fdsv)
{
    ScrollViewer sc = FindVisualChildren<ScrollViewer>(fdsv).First() as ScrollViewer;
    if (sc != null)
        sc.ScrollToEnd();
}


public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

Upvotes: 3

Shashi Bhushan
Shashi Bhushan

Reputation: 1350

You can access scrollviewer from flowdocumentscrollviewer. Here is example

 private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var scrollViewer = FindScrollViewer(flowDocumentScrollViewer);
        scrollViewer.ScrollToBottom();
    }

    public static ScrollViewer FindScrollViewer(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;
    }

Upvotes: 2

Related Questions