[C# UWP] How do I reach all MediaPlayer elements in a GridView?

SpectraCoder 141 Reputation points
2020-03-09T06:31:25.897+00:00

In my app I have a page with a GridView with a DataTemplate that has a MediaPlayer element that is bound to a list of sources. Each MediaPlayer element has to stop playing when the user leaves the page. I wanted to solve this by pausing the MediaPlayers when the user clicks a button that goes to another page, but I can't get my head around on how to pause the players when they are generated by the GridView.

How do I reach each instance of the MediaPlayer to be able to pause them?

<GridView Name="Gridview" Grid.Row="1" ItemsSource="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" SelectionMode="None">  
            <GridView.ItemTemplate>  
                <DataTemplate x:DataType="local:TutorialVideo">  
                    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">  
  
                        <TextBlock Text="{Binding Title}" Style="{ThemeResource SubheaderTextBlockStyle}" Margin="10"/>                          
                        <MediaPlayerElement Name="player" MinWidth="500" MaxWidth="800" AreTransportControlsEnabled="True" Source="{Binding Source}" Margin="10"/>                          
                    </StackPanel>  
                </DataTemplate>  
            </GridView.ItemTemplate>  
</GridView>  
Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. SpectraCoder 141 Reputation points
    2020-03-09T19:09:53.437+00:00

    Never mind, solved it! I used this piece of code I found online:

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject objectToSearchThrough) where T : DependencyObject  
            {  
                if (objectToSearchThrough != null)  
                {  
                    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(objectToSearchThrough); i++)  
                    {  
                        DependencyObject child = VisualTreeHelper.GetChild(objectToSearchThrough, i);  
                        if (child != null && child is T)  
                        {  
                            yield return (T)child;  
                        }  
      
                        foreach (T childOfChild in FindVisualChildren<T>(child))  
                        {  
                            yield return childOfChild;  
                        }  
                    }  
                }  
            }         
    

    I used this method in a foreach statement:

    foreach(var player in FindVisualChildren<MediaPlayerElement>(Gridview))  
                {  
                    player.MediaPlayer.Pause();  
                }  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.