开发者

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!


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);
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜