Julian
Julian

Reputation: 1294

WinRT - determine if an element is visible to the user

I need to autoplay a media file if the user scrolls it into the view.

I got something like this:

<ScrollViewer>
   <ItemsControl ItemsSource="{Binding SelectedProduct.Entities}" ItemTemplateSelector="{StaticResource EntityDataTemplateSelector}" />             
</ScrollViewer>

In one of those DataTemplates I am using a media-player of the PlayerFramework (PlayerFramework on codeplex).

As the user scrolls the media-player (manually) into the view. The video shall start to play.

My problem is: How can I determine if an element is in viewport?

I went with this post early but its not working on winrt.

Hopefully you can help me. Thanks in advance!

Julian

Upvotes: 1

Views: 1512

Answers (1)

Julian
Julian

Reputation: 1294

I could fix the problem by adjusting the method from this post to:

private bool IsVisibileToUser ( FrameworkElement element, FrameworkElement container )
    {
        if ( element == null || container == null )
            return false;

        if ( element.Visibility != Visibility.Visible )
            return false;

        Rect elementBounds = element.TransformToVisual( container ).TransformBounds( new Rect( 0.0, 0.0, element.ActualWidth, element.ActualHeight ) );
        Rect containerBounds = new Rect( 0.0, 0.0, container.ActualWidth, container.ActualHeight );

        return (elementBounds.Top < containerBounds.Bottom && elementBounds.Bottom > containerBounds.Top);
    }

This only works for vertical scrolling. If you need it for horizontal scrolling you need to modify the return value at the end of the method.

Best regards Julian

Upvotes: 3

Related Questions