Categories: Blog

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.

Jeff Prosise

Recent Posts

8-Step AWS to Microsoft Azure Migration Strategy

Microsoft Azure and Amazon Web Services (AWS) are two of the most popular cloud platforms.…

2 weeks ago

How to Navigate Azure Governance

 Cloud management is difficult to do manually, especially if you work with multiple cloud…

3 weeks ago

Why Azure’s Scalability is Your Key to Business Growth & Efficiency

Azure’s scalable infrastructure is often cited as one of the primary reasons why it's the…

1 month ago

Unlocking the Power of AI in your Software Development Life Cycle (SDLC)

https://www.youtube.com/watch?v=wDzCN0d8SeA Watch our "Unlocking the Power of AI in your Software Development Life Cycle (SDLC)"…

2 months ago

The Role of FinOps in Accelerating Business Innovation

FinOps is a strategic approach to managing cloud costs. It combines financial management best practices…

2 months ago

Azure Kubernetes Security Best Practices

Using Kubernetes with Azure combines the power of Kubernetes container orchestration and the cloud capabilities…

2 months ago