question

SpectraCoder avatar image
0 Votes"
SpectraCoder asked ·

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

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>


windows-uwpwindows-uwp-xaml
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

SpectraCoder avatar image
0 Votes"
SpectraCoder answered ·

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();
             }
· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.