我在 xaml 页面中有这样的内容:
<ScrollViewer x:Name="PreviewvideosScrollViewer" HorizontalScrollBarVisibility="Auto" Width="1366" Height="480" VerticalScrollBarVisibility="Disabled">
<Canvas x:Name="VideoCanvas" HorizontalAlignment="Left">
</Canvas>
</ScrollViewer>
在代码中,我向画布添加了许多控件,其中许多控件不在窗口中。如何确定哪些控件可见(用户在屏幕中看到),哪些不可见?
我试过这样的示例代码:
private bool IsUserVisible(FrameworkElement element)
{
if (!element.Parent.Equals(VideoCanvas))
return true;
//// position of your visual inside the scrollviewer
GeneralTransform childTransform = element.TransformToAncestor(VideoCanvas);
Rect rectangle = childTransform.TransformBounds(new Rect(new Point(0, 0), element.RenderSize));
////Check if the elements Rect intersects with that of the scrollviewer's
Rect result = Rect.Intersect(new Rect(new Point(0, 0), VideoCanvas.RenderSize), rectangle);
////if result is Empty then the element is not in view
return result != Rect.Empty;
}
或这个:
private bool IsUserVisible(FrameworkElement element, FrameworkElement container)
{
if (!element.IsVisible)
return false;
var bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
var rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
}
但两者都不起作用。哪里可能有问题?在滚动查看器中使用画布?或者是其他东西?谢谢