Determining the Visibility of Elements inside Scrollviewer

A ScrollViewer is a very handy control. One of the problems, however, is bringing a control to Focus or scrolling to the item. If this is done manually, that’s not an issue. But programmatically hmm.. You can hit some issues. The simplest way is to call the scrollviewer’s ScrollToVerticalOffset() with the offset being the Y co-ordinate. But what if the element is partially visible and you do not want it to scroll. This would require determining if the element is in the ScrollViewers viewport. The way to achieve this is simple.

Suppose ContainedObject is the element inside the Scrollviewer (ScrollViewerObj)

 

// position of your visual inside the scrollviewer   

GeneralTransform childTransform = ContainedObject.TransformToAncestor(ScrollViewerObj);

Rect rectangle = childTransform.TransformBounds(new Rect(new Point(0,0),ContainedObject.RenderSize));

//Check if the elements Rect intersects with that of the scrollviewer's
Rect result = Rect.Intersect(new Rect(new Point(0, 0), ScrollViewerObj.RenderSize),rectangle);

//if result is Empty then the element is not in view

if (result == Rect.Empty)

{

//....

}

else

{

//obj is partially Or completely visible

//skip or bring obj in view.

}

 

 

 

Share this post