How can I make the Silverlight ScrollViewer scroll to show a child control with focus?

后端 未结 4 1979
时光取名叫无心
时光取名叫无心 2021-02-05 16:30

I have a ScrollViewer which contains a Grid with multiple controls in it. The user can tab through the controls, but eventually they tab to a control that isn\'t in view - so th

4条回答
  •  心在旅途
    2021-02-05 16:58

    Just a slight enhancement. Still need to do this for Silverlight 4 by the way. Instead of GotFocus for each control you can handle the GotFocus of the scrollviewer itself and implement it just once.

     private void _ScrollViewer_GotFocus(object sender, RoutedEventArgs e)
            {
                FrameworkElement element = e.OriginalSource as FrameworkElement;
    
                if (element != null)
                {
                    ScrollViewer scrollViewer = sender as ScrollViewer;
                    scrollViewer.ScrollToVerticalOffset(GetVerticalOffset(element, scrollViewer));
                }
    
            }
    
            private double GetVerticalOffset(FrameworkElement child, ScrollViewer scrollViewer)
            {
                // Ensure the control is scrolled into view in the ScrollViewer. 
                GeneralTransform focusedVisualTransform = child.TransformToVisual(scrollViewer);
                Point topLeft = focusedVisualTransform.Transform(new Point(child.Margin.Left, child.Margin.Top));
                Rect rectangle = new Rect(topLeft, child.RenderSize);
                double newOffset = scrollViewer.VerticalOffset + (rectangle.Bottom - scrollViewer.ViewportHeight);
                return newOffset < 0 ? 0 : newOffset; // no use returning negative offset
            }
    

提交回复
热议问题