Global MediaElement that continues playing after n

2020-02-26 02:30发布

问题:

I am using a MediaElement to play music in my metro app. I want the Music keeps playing even if I navigate to another Page.

In the following Thread that question was asked also: 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 Changed the control template of the root frame to include the 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 on the Page navigated to:

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 the MediaElemt on the Root page.

I builded a little example Project to demonstrate.

Sample Project

Any Ideas ? Thanks in advance !

Best regards Fabian

回答1:

It's possible your Navigated handler where you try to get the visual tree child gets called before the visual tree is fully loaded (added to visual tree). You could try moving your 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);
    }
}