AzureFeeds - All your Azure feeds in one place.

Sponsors

Monday, March 21, 2011

Silverlight for Windows Phone Programming Tip #7

by jprosise via Wintellog on 3/21/2011 1:47:46 AM

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.

email it!bookmark it!digg it!

Original Post: Silverlight for Windows Phone Programming Tip #7

Legal Note

The content of the postings is owned by the respective author. AzureFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on AzureFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us