This project has moved. For the latest updates, please go here.

How do you scroll a CheckListBox item into view if it is not visible

May 13, 2012 at 10:56 AM

How do I scroll an item outside the visible area into view programmatically. This is really 2 questions, how do I determine programmatically if it is visible or not, and then how do I scroll it into view if it is not.

Coordinator
May 14, 2012 at 9:16 PM

Hi,

 

The CheckListBox is an ItemsControl with additionnal properties.  Unfortunately, none of these properties will help you to find out if an item is in view or not.  Here is some code that uses properties and methods that can be found on ItemsControl.

 

private void BringItemIntoView( ItemsControl control, object item )
{
  FrameworkElement container = control.ItemContainerGenerator.ContainerFromItem( item ) as FrameworkElement;
  if( container == null )
    return;

  Rect containerArea = container.TransformToVisual( control ).TransformBounds( new Rect( container.RenderSize ) );
  Rect controlArea = new Rect( control.RenderSize );

  if( controlArea.IntersectsWith( containerArea ) )
    return;

  container.BringIntoView();
}

 

Basically, we try to retrieve the container for the target item.  Once we have it, we calculate its position and size relative to the ItemsControl.  If the position is within the ItemsControl visible area, the item is in view.  Otherwise, we consider the item to be out of view.  Invoking the FrameworkElement.BringIntoView method will bring the container into the visible area.

 

I haven't tested this algorithm in all possible scenarios, so there may be some case where it fails.