在Viewport中查找WPF控件

时间:2010-11-17 12:28:52

标签: c# .net wpf

更新

这可能是一个简单或复杂的问题,但在wpf中,我有一个列表框,我从列表中填入 datatemplate

有没有办法找出特定的 datatemplate项目是否在视口中,即我已滚动到其位置并且可以查看?

目前我迷上了listbox_ScrollChanged事件,这给了我ScrollChangedEventArgs,但我找不到合适的属性......

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:5)

请参阅this问题

对于特定的ListBox,您可以执行此操作

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

来自我链接的问题的方法

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