Sunday, September 4, 2011

Is the item is visible in scroll viewer view port?

Today I am going to share an interesting trick that I learned. Some time we need to find out in WPF items control weightier an item is visible in scroll viewer view port. I am not going to put down the xaml for you rather think that we have a Listbox and there are Items inside the Listbox, and while scroll we want to find out if a item is visible in viewport or not, we might want to decorate only the items that are visible. Bellow I have put down the code which is pretty self explanatory.

        private void HandleScrollChanged(object sender, ScrollChangedEventArgs e)
{
ShowVisibleItems(sender);
}

private void ShowVisibleItems(object sender)
{
var scrollViewer = (FrameworkElement)sender;
foreach (DataItem item in listbox.Items)
{
var listBoxItem = (FrameworkElement)listbox.ItemContainerGenerator.ContainerFromItem(item);
if (IsFullyOrPartiallyVisible(listBoxItem, scrollViewer))
{
//your code goes here
}
}
}

protected bool IsFullyOrPartiallyVisible(FrameworkElement child, FrameworkElement scrollViewer)
{
var childTransform = child.TransformToAncestor(scrollViewer);
var childRectangle = childTransform.TransformBounds(new Rect(new Point(0, 0), child.RenderSize));
var ownerRectangle = new Rect(new Point(0, 0), scrollViewer.RenderSize);
return ownerRectangle.IntersectsWith(childRectangle);
}



The above code works if “var listBoxItem = (FrameworkElement)listbox.ItemContainerGenerator.ContainerFromItem(item); “ return not null that is the virtualization not enabled but if virtualization is working then it wont work, this particular code works perfectly with ItemsPanel is been customized to fill with a warpPanel.


Hope this will help some one. Till next post, Happy programming.

1 comment:

spccdt said...

Thanks, this was helpful!

Post a Comment