How to know if an item is visible to user?

2019-09-13 21:18发布

问题:

please look at this:

<Grid>
    <ScrollViewer>
        <Grid Background="Red" Width="50" Height="50" VerticalAlignment="Top" Margin="0,-50,0,0"/>
    </ScrollViewer>
</Grid>

here the red grid is not visible because of its margin. but when user pulls down, it will be visible on the screen.

How can I know when it is visible? thanks.

(It's a WP8 app, if that matters)

回答1:

This method might come handy for you.

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