Silverlight for Windows Phone Programming Tip #7

I recently worked on a phone project that required me to tombstone a MediaElement control. Basically, I needed to save the current playback position when the app was deactivated, and restore it when (and if) the app was reactivated. So I whipped up something like this:

 

protected override void OnNavigatedFrom(NavigationEventArgs e)

{

    this.State["Pos"] = Player.Position;

}

 

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    if (this.State.ContainsKey("Pos"))

    {

        Player.Position = (TimeSpan)this.State["Pos"];

        Player.Play();

    }

}

 

Unfortunately, it didn’t work. Each time the app was reactivated, playback started from the beginning. Investigation revealed that Position was being persisted in page state just fine. The problem was that the MediaElement seemed to be ignoring the Position I assigned to it in OnNavigatedTo.

That’s when it hit me. You can’t set a MediaElement’s position property when the MediaElement isn’t playing. And you’re not sure it’s playing until it fires a MediaOpened event. So one small change to the code solved the problem:

 

protected override void OnNavigatedFrom(NavigationEventArgs e)

{

    this.State["Pos"] = Player.Position;

}

 

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    if (this.State.ContainsKey("Pos"))

    {

        Player.MediaOpened += (s, x) =>

            Player.Position = (TimeSpan)this.State["Pos"];

        Player.Play();

    }

}

 

Now the MediaElement picks up right where it left off before tombstoning. Good thing to keep in mind if you, too, find yourself needing to save and restore the state of a MediaElement.

We deliver solutions that accelerate the value of Azure.

Ready to experience the full power of Microsoft Azure?

Start Today

Blog Home

Stay Connected

Upcoming Events

All Events