locked
Getting/Setting Scroll Position of a Hub Control RRS feed

  • Question

  • I would like to save the scroll position in the hub control when I am navigating to another page and set the position back where it was when I navigate back to the hub page again. I couldn't find a way to get or set the current scroll position of the hub control.

    Is there a way to do this?

    Thanks,

    Ferit

     

    Saturday, November 16, 2013 5:51 PM

Answers

  • To do this, you'll need to use the VisualTreeHelper class to find and keep a reference to the Hub's scrollviewer.  Something like this:

     // ...
    
                ScrollViewer childScrollViewer = findChildScrollViewer(yourHub);
                if (childScrollViewer != null)
                {
                    double horizOffset = (double)childScrollViewer.GetValue(ScrollViewer.HorizontalOffsetProperty);
                    double vertOffset = (double)childScrollViewer.GetValue(ScrollViewer.VerticalOffsetProperty);
                }
    
                // ...
            }
    
            private ScrollViewer findChildScrollViewer(DependencyObject toSearch)
            {
                Queue<DependencyObject> children = new Queue<DependencyObject>() ;
                children.Enqueue(toSearch);
                while (children.Count != 0)
                {
                    DependencyObject dequeued = children.Dequeue();
                    if (dequeued  is ScrollViewer)
                    {
                        return (ScrollViewer)dequeued;
                    }
                    else
                    {
                        for (int index = 0; index < VisualTreeHelper.GetChildrenCount(dequeued); index ++)
                        {
                            children.Enqueue(VisualTreeHelper.GetChild(dequeued, index));
                        }
                    }
                }
                return null;
            }

    ... once you have the object, just use GetValue() to get the values, and ScrollToFooOffset() methods to get/set the values.

    Hope this helps,

    Matt

    Tuesday, December 3, 2013 12:54 AM