cab
cab

Reputation: 385

Find WPF Controls in Viewport

Updated:

This may be an easy or a complex question, but in wpf, I have a listbox that I fill in with a datatemplate from a list.

Is there a way to find out if a particular datatemplate item is in the viewport ie, I have scrolled to its position and it is viewable?

Currently I hooked into the listbox_ScrollChanged event, and this gives me the ScrollChangedEventArgs, but I haven't found the right property...

Any help would be much appreciated, thanks!

Upvotes: 2

Views: 1914

Answers (1)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84657

See this question

For a ListBox in specific you can do this

private bool IsControlVisibleToUser(Control control)
{
    ListBoxItem listBoxItem =
        listBox.ItemContainerGenerator.ContainerFromItem(control) as ListBoxItem;
    if (listBoxItem != null)
    {
        return IsUserVisible(listBoxItem, listBox);
    }
    return false;
}

And the method from the question I linked

private bool IsUserVisible(FrameworkElement element, FrameworkElement container)
{
    if (!element.IsVisible)
        return false;
    Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
    Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
    return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
} 

Upvotes: 5

Related Questions