Global MediaElement that continues to play after going to another page

I use MediaElement to play music in my metro application. I want the music to continue playing even if I go to another page.

The following topic was asked the question: http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/241ba3b4-3e2a-4f9b-a704-87c7b1be7988/

I did what JimMan suggested 1) In App.xaml.cs The root frame control template was changed to include MediaElement

var rootFrame = new Frame(); rootFrame.Style = Resources["RootFrameStyle"] as Style; rootFrame.Navigate(typeof(HomePage), MainViewModel.Instance); Window.Current.Content = rootFrame; Window.Current.Activate(); 

2) In Styles.xaml add

 <Style x:Key="RootFrameStyle" TargetType="Frame"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Frame"> <Grid> <MediaElement x:Name="MediaPlayer" AudioCategory="BackgroundCapableMedia" AutoPlay="True" /> <ContentPresenter /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> 

3) To access the MediaElement element on the page, follow these steps:

 DendencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0); MediaElement rootMediaElement = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0); 

But VisualTreeHelper.GetChild (Window.Current.Content, 0); always returns null, even if I try to access MediaElemt on the Root page.

I built a small example to demonstrate the project.

Project example

Any ideas? Thanks in advance!

Regards Fabian

+4
source share
1 answer

Perhaps your Navigated handler, where you are trying to get a child of the visual tree, is called before the visual tree is fully loaded (added to the visual tree). You can try moving the code to the Loaded event handler.

EDIT *

I confirmed my theory by making the following change:

 public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); this.Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0); MediaElement rootMediaElement = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0); } } 
+2
source

Source: https://habr.com/ru/post/1416615/


All Articles